use crate::internal::duration::duration_string;
use rusty_bubbletea::commands;
use rusty_bubbletea::model::{Cmd, Msg};
use std::fmt;
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;
static LAST_ID: AtomicI64 = AtomicI64::new(0);
fn next_id() -> i32 {
(LAST_ID.fetch_add(1, Ordering::SeqCst)) as i32
}
pub type Option = Box<dyn FnOnce(&mut Model)>;
pub fn with_interval(interval: Duration) -> Option {
Box::new(move |m: &mut Model| {
m.interval = interval;
})
}
#[derive(Debug, Clone)]
pub struct TickMsg {
pub id: i32,
tag: i32,
}
#[derive(Debug, Clone)]
pub struct StartStopMsg {
pub id: i32,
running: bool,
}
#[derive(Debug, Clone)]
pub struct ResetMsg {
pub id: i32,
}
#[derive(Clone)]
pub struct Model {
d: Duration,
id: i32,
tag: i32,
running: bool,
pub interval: Duration,
}
impl fmt::Debug for Model {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("stopwatch::Model")
.field("id", &self.id)
.field("running", &self.running)
.field("d", &self.d)
.finish()
}
}
pub fn new(opts: Vec<Option>) -> Model {
let mut m = Model {
id: next_id(),
interval: Duration::from_secs(1),
d: Duration::ZERO,
tag: 0,
running: false,
};
for opt in opts {
opt(&mut m);
}
m
}
impl Model {
pub fn id(&self) -> i32 {
self.id
}
pub fn init(&mut self) -> Cmd {
self.start()
}
pub fn start(&mut self) -> Cmd {
let start_msg: Box<dyn Msg> = Box::new(StartStopMsg {
id: self.id,
running: true,
});
let tick_cmd = tick(self.id, self.tag, self.interval);
commands::sequence(vec![Some(Box::new(move || Some(start_msg))), tick_cmd])
}
pub fn stop(&mut self) -> Cmd {
let id = self.id;
Some(Box::new(move || {
Some(Box::new(StartStopMsg { id, running: false }))
}))
}
pub fn toggle(&mut self) -> Cmd {
if self.running {
return self.stop();
}
self.start()
}
pub fn reset(&mut self) -> Cmd {
let id = self.id;
Some(Box::new(move || Some(Box::new(ResetMsg { id }))))
}
pub fn running(&self) -> bool {
self.running
}
pub fn update(&mut self, msg: &dyn Msg) -> Cmd {
if let Some(m) = msg.as_any().downcast_ref::<StartStopMsg>() {
if m.id != self.id {
return None;
}
self.running = m.running;
return None;
}
if let Some(m) = msg.as_any().downcast_ref::<ResetMsg>() {
if m.id != self.id {
return None;
}
self.d = Duration::ZERO;
return None;
}
if let Some(m) = msg.as_any().downcast_ref::<TickMsg>() {
if !self.running || m.id != self.id {
return None;
}
if m.tag > 0 && m.tag != self.tag {
return None;
}
self.d += self.interval;
self.tag += 1;
return tick(self.id, self.tag, self.interval);
}
None
}
pub fn elapsed(&self) -> Duration {
self.d
}
pub fn view(&self) -> String {
duration_string(self.d)
}
}
fn tick(id: i32, tag: i32, d: Duration) -> Cmd {
commands::tick(d, move |_| Some(Box::new(TickMsg { id, tag })))
}