1use std::time::SystemTime;
2
3use crate::prelude::*;
4use bytes_kman::TBytes;
5
6#[derive(Default, Clone, Debug)]
7pub struct Events {
8 pub events: [Option<(SystemTime, Event)>; 20],
9 pub cursour: usize,
10
11 pub subscribers: Vec<ID>,
12}
13
14#[derive(Clone, Debug, bytes_kman::Bytes)]
15pub enum SessionEvent {
16 NewElement(ElementId),
17 NewLocation(LocationId),
18 NewModule(ModuleId),
19
20 DestroyedElement(ElementId),
21 DestroyedLocation(LocationId),
22 DestroyedModule(ModuleId),
23
24 ElementIdChanged(ElementId, ElementId),
26 LocationIdChanged(LocationId, LocationId),
27 ModuleIdChanged(ModuleId, ModuleId),
28}
29
30#[derive(Clone, Debug, bytes_kman::Bytes)]
31pub enum Event {
32 Element(ElementId, ElementNotify),
33 Location(LocationId, LocationNotify),
34 Log(ID, Log),
35 SessionEvent(SessionEvent),
36}
37
38impl Events {
39 pub fn new_event(&mut self, event: Event, session: Box<dyn TSession>) {
40 self.events[self.cursour] = Some((SystemTime::now(), event.clone()));
41 self.cursour += 1;
42 if self.cursour > 19 {
43 self.cursour = 0;
44 }
45
46 self.subscribers.retain(|subscriber| {
47 if let Ok(subscriber) = &subscriber.get_ref(session.as_ref()) {
48 let _ = subscriber.notify(event.clone());
49 true
50 } else {
51 false
52 }
53 })
54 }
55
56 pub fn is_subscribed(&self, _ref: &ID) -> bool {
57 for r in self.subscribers.iter() {
58 if r == _ref {
59 return true;
60 }
61 }
62 false
63 }
64
65 pub fn subscribe(&mut self, _ref: ID) -> bool {
66 if self.is_subscribed(&_ref) {
67 return false;
68 }
69
70 self.subscribers.push(_ref);
71
72 true
73 }
74
75 pub fn unsubscribe(&mut self, _ref: ID) -> bool {
76 if !self.is_subscribed(&_ref) {
77 return false;
78 }
79
80 self.subscribers.retain(|e| *e != _ref);
81
82 true
83 }
84}