scirs2_metrics/visualization/advanced_interactive/
events.rs

1//! Event system for interactive visualization
2//!
3//! This module provides event handling, routing, and management for
4//! interactive dashboard components.
5
6#![allow(clippy::too_many_arguments)]
7#![allow(dead_code)]
8
9use super::widgets::{WidgetEvent, WidgetEventResponse};
10use crate::error::{MetricsError, Result};
11use serde::{Deserialize, Serialize};
12use serde_json::Value;
13use std::collections::{HashMap, VecDeque};
14use std::sync::{Arc, Mutex};
15use std::time::Instant;
16
17/// Event system for managing dashboard interactions
18#[derive(Debug)]
19pub struct EventSystem {
20    /// Event handlers
21    handlers: HashMap<String, Vec<Box<dyn EventHandler + Send + Sync>>>,
22    /// Event queue
23    event_queue: VecDeque<DashboardEvent>,
24    /// Event history
25    event_history: VecDeque<DashboardEvent>,
26    /// Configuration
27    config: EventSystemConfig,
28}
29
30/// Event handler trait
31pub trait EventHandler: std::fmt::Debug + Send + Sync {
32    /// Handle event
33    fn handle_event(&self, event: &DashboardEvent) -> Result<Option<EventResponse>>;
34
35    /// Get handler priority
36    fn priority(&self) -> u32;
37
38    /// Check if handler can handle event type
39    fn can_handle(&self, event_type: &str) -> bool;
40}
41
42/// Dashboard event
43#[derive(Debug, Clone)]
44pub struct DashboardEvent {
45    /// Event ID
46    pub id: String,
47    /// Event type
48    pub event_type: String,
49    /// Source widget or component
50    pub source: String,
51    /// Target widget or component
52    pub target: Option<String>,
53    /// Event timestamp
54    pub timestamp: Instant,
55    /// Event data
56    pub data: HashMap<String, Value>,
57    /// Event metadata
58    pub metadata: EventMetadata,
59}
60
61/// Event metadata
62#[derive(Debug, Clone)]
63pub struct EventMetadata {
64    /// User session ID
65    pub session_id: Option<String>,
66    /// User ID
67    pub user_id: Option<String>,
68    /// Event priority
69    pub priority: EventPriority,
70    /// Propagation settings
71    pub propagation: PropagationSettings,
72    /// Context information
73    pub context: HashMap<String, Value>,
74}
75
76/// Event priority enumeration
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub enum EventPriority {
79    /// Low priority
80    Low,
81    /// Normal priority
82    Normal,
83    /// High priority
84    High,
85    /// Critical priority
86    Critical,
87}
88
89/// Propagation settings
90#[derive(Debug, Clone)]
91pub struct PropagationSettings {
92    /// Stop propagation
93    pub stop_propagation: bool,
94    /// Prevent default
95    pub prevent_default: bool,
96    /// Bubble up
97    pub bubble: bool,
98    /// Capture phase
99    pub capture: bool,
100}
101
102/// Event response
103#[derive(Debug, Clone)]
104pub struct EventResponse {
105    /// Response ID
106    pub id: String,
107    /// Actions to perform
108    pub actions: Vec<EventAction>,
109    /// Response data
110    pub data: HashMap<String, Value>,
111    /// Should stop propagation
112    pub stop_propagation: bool,
113}
114
115/// Event action enumeration
116#[derive(Debug, Clone)]
117pub enum EventAction {
118    /// Update widget
119    UpdateWidget {
120        widget_id: String,
121        updates: HashMap<String, Value>,
122    },
123    /// Trigger new event
124    TriggerEvent(DashboardEvent),
125    /// Execute script
126    ExecuteScript {
127        script: String,
128        context: HashMap<String, Value>,
129    },
130    /// Send notification
131    SendNotification {
132        message: String,
133        level: NotificationLevel,
134    },
135    /// Update data source
136    UpdateDataSource { source_id: String, data: Value },
137    /// Custom action
138    Custom {
139        action_type: String,
140        parameters: HashMap<String, Value>,
141    },
142}
143
144/// Notification level
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub enum NotificationLevel {
147    /// Info notification
148    Info,
149    /// Success notification
150    Success,
151    /// Warning notification
152    Warning,
153    /// Error notification
154    Error,
155}
156
157/// Event system configuration
158#[derive(Debug, Clone, Serialize, Deserialize)]
159pub struct EventSystemConfig {
160    /// Maximum event queue size
161    pub max_queue_size: usize,
162    /// Maximum history size
163    pub max_history_size: usize,
164    /// Event processing batch size
165    pub batch_size: usize,
166    /// Enable event debugging
167    pub debug_enabled: bool,
168    /// Performance monitoring
169    pub performance_monitoring: bool,
170}
171
172impl EventSystem {
173    /// Create new event system
174    pub fn new(config: EventSystemConfig) -> Self {
175        Self {
176            handlers: HashMap::new(),
177            event_queue: VecDeque::new(),
178            event_history: VecDeque::new(),
179            config,
180        }
181    }
182
183    /// Register event handler
184    pub fn register_handler(
185        &mut self,
186        event_type: String,
187        handler: Box<dyn EventHandler + Send + Sync>,
188    ) {
189        self.handlers.entry(event_type).or_default().push(handler);
190    }
191
192    /// Queue event for processing
193    pub fn queue_event(&mut self, event: DashboardEvent) -> Result<()> {
194        if self.event_queue.len() >= self.config.max_queue_size {
195            return Err(MetricsError::ComputationError(
196                "Event queue is full".to_string(),
197            ));
198        }
199
200        self.event_queue.push_back(event);
201        Ok(())
202    }
203
204    /// Process queued events
205    pub fn process_events(&mut self) -> Result<Vec<EventResponse>> {
206        let mut responses = Vec::new();
207        let batch_size = self.config.batch_size.min(self.event_queue.len());
208
209        for _ in 0..batch_size {
210            if let Some(event) = self.event_queue.pop_front() {
211                if let Ok(response) = self.process_single_event(&event) {
212                    if let Some(resp) = response {
213                        responses.push(resp);
214                    }
215                }
216
217                // Add to history
218                self.add_to_history(event);
219            }
220        }
221
222        Ok(responses)
223    }
224
225    /// Process single event
226    fn process_single_event(&self, event: &DashboardEvent) -> Result<Option<EventResponse>> {
227        if let Some(handlers) = self.handlers.get(&event.event_type) {
228            // Sort handlers by priority
229            let mut sorted_handlers: Vec<_> = handlers.iter().collect();
230            sorted_handlers.sort_by(|a, b| b.priority().cmp(&a.priority()));
231
232            for handler in sorted_handlers {
233                if handler.can_handle(&event.event_type) {
234                    if let Ok(Some(response)) = handler.handle_event(event) {
235                        if response.stop_propagation {
236                            return Ok(Some(response));
237                        }
238                        return Ok(Some(response));
239                    }
240                }
241            }
242        }
243
244        Ok(None)
245    }
246
247    /// Add event to history
248    fn add_to_history(&mut self, event: DashboardEvent) {
249        if self.event_history.len() >= self.config.max_history_size {
250            self.event_history.pop_front();
251        }
252        self.event_history.push_back(event);
253    }
254
255    /// Get event history
256    pub fn get_history(&self, limit: Option<usize>) -> Vec<DashboardEvent> {
257        let limit = limit.unwrap_or(self.event_history.len());
258        self.event_history
259            .iter()
260            .rev()
261            .take(limit)
262            .cloned()
263            .collect()
264    }
265
266    /// Clear event queue
267    pub fn clear_queue(&mut self) {
268        self.event_queue.clear();
269    }
270
271    /// Get queue size
272    pub fn queue_size(&self) -> usize {
273        self.event_queue.len()
274    }
275}
276
277impl Default for EventSystemConfig {
278    fn default() -> Self {
279        Self {
280            max_queue_size: 1000,
281            max_history_size: 5000,
282            batch_size: 50,
283            debug_enabled: false,
284            performance_monitoring: true,
285        }
286    }
287}
288
289impl Default for EventMetadata {
290    fn default() -> Self {
291        Self {
292            session_id: None,
293            user_id: None,
294            priority: EventPriority::Normal,
295            propagation: PropagationSettings::default(),
296            context: HashMap::new(),
297        }
298    }
299}
300
301impl Default for PropagationSettings {
302    fn default() -> Self {
303        Self {
304            stop_propagation: false,
305            prevent_default: false,
306            bubble: true,
307            capture: false,
308        }
309    }
310}