use chrono::{DateTime, Duration, Local};
#[derive(Debug, Clone)]
pub struct TimerData {
pub total: Duration,
pub remaining: Duration,
pub start_moments: Vec<DateTime<Local>>, pub pause_moments: Vec<DateTime<Local>>, }
impl TimerData {
fn new(duration: Duration) -> Self {
Self {
total: duration,
remaining: duration,
start_moments: Vec::new(),
pause_moments: Vec::new(),
}
}
pub fn start(&self) -> DateTime<Local> {
self.start_moments[0]
}
pub fn stop(&self) -> DateTime<Local> {
self.pause_moments[self.pause_moments.len() - 1]
}
pub fn duration_expected(&self) -> Duration {
self.total
}
pub fn duration_actual(&self) -> Duration {
self.stop() - self.start()
}
}
#[derive(Clone, Debug)]
pub struct Timer {
pub paused: bool,
pub data: TimerData,
}
impl Timer {
pub fn new(duration: Duration) -> Self {
Self {
paused: true, data: TimerData::new(duration),
}
}
pub fn read(&self) -> Duration {
if self.paused {
self.data.remaining
} else {
self.data.remaining - (Local::now() - self.last_start())
}
}
pub fn pause_or_resume(&mut self) {
if self.paused {
self.resume();
} else {
self.pause();
}
}
pub fn pause(&mut self) {
let moment = Local::now();
self.data.pause_moments.push(moment);
self.data.remaining = self.data.remaining - (moment - self.last_start());
self.paused = true;
}
pub fn resume(&mut self) {
self.data.start_moments.push(Local::now());
self.paused = false;
}
pub fn stop(&mut self) -> TimerData {
self.data.pause_moments.push(Local::now());
let duration = self.data.total;
let data = std::mem::replace(&mut self.data, TimerData::new(duration));
data
}
fn last_start(&self) -> DateTime<Local> {
self.data.start_moments[self.data.start_moments.len() - 1]
}
}