1use chrono::DateTime;
2use chrono::Duration;
3use chrono::Utc;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use serde_json::Map;
7use serde_json::Value;
8
9use crate::duration::DurationSerialization;
10use crate::TimeInterval;
11
12#[derive(Serialize, Deserialize, JsonSchema, Clone, Debug)]
13pub struct Event {
14 pub id: Option<i64>,
20 pub timestamp: DateTime<Utc>,
22 #[serde(with = "DurationSerialization", default = "default_duration")]
26 #[schemars(with = "f64")]
27 pub duration: Duration,
28 pub data: Map<String, Value>,
31}
32
33impl Event {
34 pub fn calculate_endtime(&self) -> DateTime<Utc> {
35 self.timestamp
36 + chrono::Duration::nanoseconds(self.duration.num_nanoseconds().unwrap() as i64)
37 }
38 pub fn interval(&self) -> TimeInterval {
39 TimeInterval::new(self.timestamp, self.calculate_endtime())
40 }
41}
42
43impl PartialEq for Event {
44 fn eq(&self, other: &Event) -> bool {
45 !(self.timestamp != other.timestamp
46 || self.duration != other.duration
47 || self.data != other.data)
48 }
49}
50
51impl Default for Event {
52 fn default() -> Self {
53 Event {
54 id: None,
55 timestamp: Utc::now(),
56 duration: Duration::seconds(0),
57 data: serde_json::Map::new(),
58 }
59 }
60}
61
62fn default_duration() -> Duration {
63 Duration::seconds(0)
64}
65
66#[test]
67fn test_event() {
68 use serde_json::json;
69
70 let e = Event {
71 id: None,
72 timestamp: Utc::now(),
73 duration: Duration::seconds(1),
74 data: json_map! {"test": json!(1)},
75 };
76 debug!("event: {:?}", e);
77}