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
use crate::flow::core::{Flow, TimedEvent};
use crate::io::provider::{StreamType, Timestamp};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToggleState {
    // IMMUTABLE
    pub caption: String,

    // MUTABLE
    pub active: bool,
    pub last_toggle: Option<Timestamp>,
}

#[allow(clippy::new_without_default)]
impl ToggleState {
    pub fn new(caption: String, active: bool) -> Self {
        Self {
            caption,
            active,
            last_toggle: None,
        }
    }

    pub fn toggle_action(&self) -> ToggleAction {
        ToggleAction::new(!self.active)
    }
}

impl Flow for ToggleState {
    type Action = ToggleAction;
    type Event = ToggleEvent;

    fn stream_type() -> StreamType {
        StreamType::from("rillrate.flow.control.toggle.v0")
    }

    fn apply(&mut self, event: TimedEvent<Self::Event>) {
        self.active = event.event.active;
        self.last_toggle = Some(event.timestamp);
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToggleAction {
    pub set_active: bool,
}

impl ToggleAction {
    pub fn new(set_active: bool) -> Self {
        Self { set_active }
    }

    pub fn on() -> Self {
        Self { set_active: true }
    }

    pub fn off() -> Self {
        Self { set_active: false }
    }

    pub fn into_value(self) -> bool {
        self.set_active
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToggleEvent {
    pub active: bool,
}