#![allow(clippy::too_many_arguments)]
#![allow(dead_code)]
use super::widgets::{WidgetEvent, WidgetEventResponse};
use crate::error::{MetricsError, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Instant;
#[derive(Debug)]
pub struct EventSystem {
handlers: HashMap<String, Vec<Box<dyn EventHandler + Send + Sync>>>,
event_queue: VecDeque<DashboardEvent>,
event_history: VecDeque<DashboardEvent>,
config: EventSystemConfig,
}
pub trait EventHandler: std::fmt::Debug + Send + Sync {
fn handle_event(&self, event: &DashboardEvent) -> Result<Option<EventResponse>>;
fn priority(&self) -> u32;
fn can_handle(&self, event_type: &str) -> bool;
}
#[derive(Debug, Clone)]
pub struct DashboardEvent {
pub id: String,
pub event_type: String,
pub source: String,
pub target: Option<String>,
pub timestamp: Instant,
pub data: HashMap<String, Value>,
pub metadata: EventMetadata,
}
#[derive(Debug, Clone)]
pub struct EventMetadata {
pub session_id: Option<String>,
pub user_id: Option<String>,
pub priority: EventPriority,
pub propagation: PropagationSettings,
pub context: HashMap<String, Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventPriority {
Low,
Normal,
High,
Critical,
}
#[derive(Debug, Clone)]
pub struct PropagationSettings {
pub stop_propagation: bool,
pub prevent_default: bool,
pub bubble: bool,
pub capture: bool,
}
#[derive(Debug, Clone)]
pub struct EventResponse {
pub id: String,
pub actions: Vec<EventAction>,
pub data: HashMap<String, Value>,
pub stop_propagation: bool,
}
#[derive(Debug, Clone)]
pub enum EventAction {
UpdateWidget {
widget_id: String,
updates: HashMap<String, Value>,
},
TriggerEvent(DashboardEvent),
ExecuteScript {
script: String,
context: HashMap<String, Value>,
},
SendNotification {
message: String,
level: NotificationLevel,
},
UpdateDataSource { source_id: String, data: Value },
Custom {
action_type: String,
parameters: HashMap<String, Value>,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NotificationLevel {
Info,
Success,
Warning,
Error,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EventSystemConfig {
pub max_queue_size: usize,
pub max_history_size: usize,
pub batch_size: usize,
pub debug_enabled: bool,
pub performance_monitoring: bool,
}
impl EventSystem {
pub fn new(config: EventSystemConfig) -> Self {
Self {
handlers: HashMap::new(),
event_queue: VecDeque::new(),
event_history: VecDeque::new(),
config,
}
}
pub fn register_handler(
&mut self,
event_type: String,
handler: Box<dyn EventHandler + Send + Sync>,
) {
self.handlers.entry(event_type).or_default().push(handler);
}
pub fn queue_event(&mut self, event: DashboardEvent) -> Result<()> {
if self.event_queue.len() >= self.config.max_queue_size {
return Err(MetricsError::ComputationError(
"Event queue is full".to_string(),
));
}
self.event_queue.push_back(event);
Ok(())
}
pub fn process_events(&mut self) -> Result<Vec<EventResponse>> {
let mut responses = Vec::new();
let batch_size = self.config.batch_size.min(self.event_queue.len());
for _ in 0..batch_size {
if let Some(event) = self.event_queue.pop_front() {
if let Ok(response) = self.process_single_event(&event) {
if let Some(resp) = response {
responses.push(resp);
}
}
self.add_to_history(event);
}
}
Ok(responses)
}
fn process_single_event(&self, event: &DashboardEvent) -> Result<Option<EventResponse>> {
if let Some(handlers) = self.handlers.get(&event.event_type) {
let mut sorted_handlers: Vec<_> = handlers.iter().collect();
sorted_handlers.sort_by(|a, b| b.priority().cmp(&a.priority()));
for handler in sorted_handlers {
if handler.can_handle(&event.event_type) {
if let Ok(Some(response)) = handler.handle_event(event) {
if response.stop_propagation {
return Ok(Some(response));
}
return Ok(Some(response));
}
}
}
}
Ok(None)
}
fn add_to_history(&mut self, event: DashboardEvent) {
if self.event_history.len() >= self.config.max_history_size {
self.event_history.pop_front();
}
self.event_history.push_back(event);
}
pub fn get_history(&self, limit: Option<usize>) -> Vec<DashboardEvent> {
let limit = limit.unwrap_or(self.event_history.len());
self.event_history
.iter()
.rev()
.take(limit)
.cloned()
.collect()
}
pub fn clear_queue(&mut self) {
self.event_queue.clear();
}
pub fn queue_size(&self) -> usize {
self.event_queue.len()
}
}
impl Default for EventSystemConfig {
fn default() -> Self {
Self {
max_queue_size: 1000,
max_history_size: 5000,
batch_size: 50,
debug_enabled: false,
performance_monitoring: true,
}
}
}
impl Default for EventMetadata {
fn default() -> Self {
Self {
session_id: None,
user_id: None,
priority: EventPriority::Normal,
propagation: PropagationSettings::default(),
context: HashMap::new(),
}
}
}
impl Default for PropagationSettings {
fn default() -> Self {
Self {
stop_propagation: false,
prevent_default: false,
bubble: true,
capture: false,
}
}
}