mod control;
use super::next_id;
use super::timer::go_duration;
use crate::{Cmd, Msg as TeaMsg};
use std::time::{Duration, SystemTime};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Msg {
StartStop {
id: u64,
running: bool,
at: SystemTime,
},
Reset {
id: u64,
at: SystemTime,
},
Tick {
id: u64,
at: SystemTime,
tag: u64,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Model {
pub interval: Duration,
elapsed: Duration,
start: Option<SystemTime>,
id: u64,
tag: u64,
running: bool,
}
impl Default for Model {
fn default() -> Self {
Self::new()
}
}
impl Model {
#[must_use]
pub fn new() -> Self {
Self {
interval: Duration::from_secs(1),
elapsed: Duration::ZERO,
start: None,
id: next_id(),
tag: 0,
running: false,
}
}
#[must_use]
pub const fn with_interval(mut self, interval: Duration) -> Self {
self.interval = interval;
self
}
#[must_use]
pub const fn id(&self) -> u64 {
self.id
}
pub fn init(&self) -> Cmd<Msg> {
self.start()
}
#[must_use]
pub const fn running(&self) -> bool {
self.running
}
pub fn update(&mut self, msg: &TeaMsg<Msg>) -> Cmd<Msg> {
match msg {
TeaMsg::App(Msg::StartStop { id, running, at }) if *id == self.id => {
self.start_stop(*running, *at);
}
TeaMsg::App(Msg::Reset { id, at }) if *id == self.id => {
self.elapsed = Duration::ZERO;
self.start = Some(*at);
}
TeaMsg::App(Msg::Tick { id, at, tag }) if self.running && *id == self.id => {
return self.on_tick(*at, *tag);
}
_ => {}
}
Cmd::none()
}
fn start_stop(&mut self, running: bool, at: SystemTime) {
match (self.running, running) {
(false, true) => self.start = Some(at),
(true, false) => self.count(at),
_ => {}
}
self.running = running;
}
fn on_tick(&mut self, at: SystemTime, tag: u64) -> Cmd<Msg> {
if tag > 0 && tag != self.tag {
return Cmd::none();
}
self.count(at);
self.tag += 1;
tick(self.id, self.tag, self.interval)
}
fn count(&mut self, at: SystemTime) {
let since = self
.start
.and_then(|s| at.duration_since(s).ok())
.unwrap_or_default();
self.elapsed += since;
self.start = Some(at);
}
#[must_use]
pub const fn elapsed(&self) -> Duration {
self.elapsed
}
#[must_use]
pub fn view(&self) -> String {
let step = if self.interval.is_zero() {
Duration::from_secs(1)
} else {
self.interval
};
let steps = self.elapsed.as_nanos() / step.as_nanos();
let cut = step.checked_mul(u32::try_from(steps).unwrap_or(u32::MAX));
go_duration(cut.unwrap_or(self.elapsed))
}
}
fn tick(id: u64, tag: u64, interval: Duration) -> Cmd<Msg> {
crate::tick(interval, move |at| Msg::Tick { id, at, tag })
}
#[cfg(test)]
mod tests;