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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
use dioxus::prelude::*;
use std::fmt::Display;

#[cfg(target_arch = "wasm32")]
use async_std::task::sleep;
#[cfg(target_arch = "wasm32")]
use instant::{Duration, Instant};
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
#[cfg(not(target_arch = "wasm32"))]
use tokio::time::sleep;

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TimerState {
    Inactive,
    Working,
    Finished,
    Paused,
}

impl Display for TimerState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            TimerState::Inactive => "Inactive",
            TimerState::Working => "Working",
            TimerState::Finished => "Finished",
            TimerState::Paused => "Paused",
        };
        write!(f, "{text}")
    }
}

#[derive(Debug, Clone)]
pub struct DioxusTimer {
    preset_duration: Duration,
    target_time: Instant,
    state: TimerState,
    /// Stores Instant::now()
    current_time: Instant,
    /// Stores paused time
    paused_time: Option<Instant>,
}

impl DioxusTimer {
    /// Creates a new `DioxusTimer` instance with default settings.
    pub fn new() -> Self {
        let current_time = Instant::now();
        let target_time = current_time;
        Self {
            preset_duration: Duration::ZERO,
            target_time,
            state: TimerState::Inactive,
            current_time,
            paused_time: None,
        }
    }

    /// Sets the preset duration for the timer.
    pub fn set_preset_time(&mut self, preset_duration: Duration) {
        if self.state == TimerState::Finished {
            return;
        }
        self.preset_duration = preset_duration;
        self.target_time = self
            .current_time
            .checked_add(preset_duration)
            .unwrap_or(self.current_time);
    }

    /// Returns the remaining time on the timer.
    pub fn remaining_time(&self) -> Duration {
        self.target_time
            .checked_duration_since(self.current_time)
            .unwrap_or(Duration::ZERO)
    }

    /// Returns the current state of the timer.
    pub fn state(&self) -> TimerState {
        self.state
    }

    /// Starts the timer if it is in the `Inactive` state.
    ///
    /// If the preset duration is zero, the method does nothing.
    pub fn start(&mut self) {
        match self.state {
            TimerState::Inactive => {
                if self.preset_duration.is_zero() {
                    return;
                }
                self.target_time = self
                    .current_time
                    .checked_add(self.preset_duration)
                    .unwrap_or(self.current_time);
                self.state = TimerState::Working;
            }
            TimerState::Paused => {
                self.state = TimerState::Working;
            }
            _ => {}
        }
    }

    /// Pauses the timer if it is in the `Working` state.
    pub fn pause(&mut self) {
        if let TimerState::Working = self.state {
            self.state = TimerState::Paused;
            self.paused_time = Some(Instant::now());
        }
    }

    /// Resets the timer to its initial state or sets the target time for a new cycle.
    ///
    /// If the timer is in the `Finished` state, it transitions to the `Inactive` state.
    pub fn reset(&mut self) {
        if self.state == TimerState::Finished {
            self.state = TimerState::Inactive;
            return;
        }
        self.target_time = self
            .current_time
            .checked_add(self.preset_duration)
            .unwrap_or(self.current_time);
    }

    /// Updates the timer's current time and checks for state transitions.
    ///
    /// The `Working` state transitions to `Finished` when the target time is reached.
    /// The `Paused` state adjusts the target time based on the time paused.
    /// The `Inactive` state resets the timer.
    pub fn update(&mut self) {
        self.current_time = Instant::now();
        match self.state {
            TimerState::Working => {
                if self
                    .target_time
                    .checked_duration_since(self.current_time)
                    .is_none()
                {
                    self.state = TimerState::Finished;
                }
            }
            TimerState::Paused => {
                self.target_time = self
                    .target_time
                    .checked_add(self.current_time - self.paused_time.unwrap())
                    .unwrap_or(self.current_time);
                self.paused_time = Some(self.current_time);
            }
            TimerState::Inactive => {
                self.reset();
            }
            _ => {}
        }
    }
}

impl Default for DioxusTimer {
    fn default() -> Self {
        Self::new()
    }
}

impl Display for DioxusTimer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let rem_time = self.remaining_time().as_secs();
        write!(
            f,
            "{:0>2}:{:0>2}:{:0>2}",
            rem_time / 3600,
            rem_time % 3600 / 60,
            rem_time % 60,
        )
    }
}

/// Manages a DioxusTimer instance within the Dioxus GUI framework using the provided `Scope`.
///
/// # Returns
///
/// Returns a `UseState` containing the DioxusTimer instance.
///
/// # Examples
///
/// ```
/// let timer = dioxus_timer::use_timer(cx, Duration::from_millis(16));
/// use_effect(cx, (), |()| {
///     let timer = timer.clone();
///     async move {
///         timer.make_mut().set_preset_time(Duration::from_secs(10));
///         timer.make_mut().start();
///     }
/// });
/// render!("{timer}")
/// ```
pub fn use_timer(cx: Scope, tick: Duration) -> UseState<DioxusTimer> {
    let timer = use_state(cx, DioxusTimer::new);

    use_future!(cx, || {
        let timer = timer.clone();
        async move {
            loop {
                timer.make_mut().update();
                sleep(tick).await;
            }
        }
    });
    timer.clone()
}

/// Manages a shared DioxusTimer instance within the Dioxus GUI framework using the provided `Scope`.
///
/// # Examples
///
/// ```
/// dioxus_timer::use_shared_timer(cx, Duration::from_millis(16));
/// let timer = use_shared_state::<dioxus_timer::DioxusTimer>(cx)?;
/// let state = timer.read().state();
/// let start_handle = move |_| { timer.write().start(); };
/// ```
pub fn use_shared_timer(cx: Scope, tick: Duration) {
    use_shared_state_provider(cx, DioxusTimer::new);
    let timer = use_shared_state::<DioxusTimer>(cx).unwrap();

    use_future!(cx, || {
        to_owned![timer];
        async move {
            loop {
                timer.write().update();
                sleep(tick).await;
            }
        }
    });
}