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
85
/*
   Appellation: event <module>
   Contrib: FL03 <jo3mccain@icloud.com>
   Description: ... Summary ...
*/
use super::{EventSpec, Eventful};
use scsys::prelude::Message;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Event<E: ToString = super::Events> {
    pub event: E,
    pub message: Message,
}

impl<E: ToString> Event<E> {
    pub fn new(event: E, message: Option<Message>) -> Self {
        Self {
            event,
            message: message.unwrap_or_default(),
        }
    }
}

impl<E: ToString> std::fmt::Display for Event<E>
where
    E: Serialize,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            scsys::fnl_remove(serde_json::to_string(&self).unwrap())
        )
    }
}

impl<E: ToString> Default for Event<E>
where
    E: Default,
{
    fn default() -> Self {
        Self::new(Default::default(), None)
    }
}

impl<E: ToString> Eventful for Event<E>
where
    E: Clone,
{
    type Event = E;

    fn event(&self) -> Self::Event {
        self.event.clone()
    }
}

impl<E: ToString> EventSpec for Event<E>
where
    E: Clone,
{
    type Data = serde_json::Value;

    fn message(&self) -> &scsys::prelude::Message<Self::Data> {
        &self.message
    }
}

impl<E: ToString> From<E> for Event<E> {
    fn from(data: E) -> Self {
        Self::new(data, None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::events::Events;

    #[test]
    fn test_events_default() {
        let a = Event::<Events>::default();
        assert_eq!(a.event(), crate::events::Events::None);
    }
}