1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::time::SystemTime;

use crate::prelude::*;
use bytes_kman::TBytes;

#[derive(Default, Clone, Debug)]
pub struct Events {
    pub events: [Option<(SystemTime, Event)>; 20],
    pub cursour: usize,

    pub subscribers: Vec<ID>,
}

#[derive(Clone, Debug, bytes_kman::Bytes)]
pub enum SessionEvent {
    NewElement(ElementId),
    NewLocation(LocationId),
    NewModule(ModuleId),

    DestroyedElement(ElementId),
    DestroyedLocation(LocationId),
    DestroyedModule(ModuleId),

    // old, new
    ElementIdChanged(ElementId, ElementId),
    LocationIdChanged(LocationId, LocationId),
    ModuleIdChanged(ModuleId, ModuleId),
}

#[derive(Clone, Debug, bytes_kman::Bytes)]
pub enum Event {
    Element(ElementId, ElementNotify),
    Location(LocationId, LocationNotify),
    Log(ID, Log),
    SessionEvent(SessionEvent),
}

impl Events {
    pub fn new_event(&mut self, event: Event, session: Box<dyn TSession>) {
        self.events[self.cursour] = Some((SystemTime::now(), event.clone()));
        self.cursour += 1;
        if self.cursour > 19 {
            self.cursour = 0;
        }

        self.subscribers.retain(|subscriber| {
            if let Ok(subscriber) = &subscriber.get_ref(session.as_ref()) {
                let _ = subscriber.notify(event.clone());
                true
            } else {
                false
            }
        })
    }

    pub fn is_subscribed(&self, _ref: &ID) -> bool {
        for r in self.subscribers.iter() {
            if r == _ref {
                return true;
            }
        }
        false
    }

    pub fn subscribe(&mut self, _ref: ID) -> bool {
        if self.is_subscribed(&_ref) {
            return false;
        }

        self.subscribers.push(_ref);

        true
    }

    pub fn unsubscribe(&mut self, _ref: ID) -> bool {
        if !self.is_subscribed(&_ref) {
            return false;
        }

        self.subscribers.retain(|e| *e != _ref);

        true
    }
}