timers/src/pomodoro.rs

91 lines
2.2 KiB
Rust
Raw Normal View History

2023-07-29 12:15:19 +02:00
use std::{fmt::Display, time::Duration};
use serde::{Deserialize, Serialize};
use crate::daemon::Timer;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Pomodoro {
work: Duration,
pause: Duration,
long_pause: Duration,
pauses_till_long: u64,
pauses: u64,
status: Status,
pub timer: Timer,
}
impl Display for Pomodoro {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Pomodoro ({:?}, {:?}, {:?}) currently {} with {:?} remaining.",
self.work,
self.pause,
self.long_pause,
self.status,
self.timer.remaining()
)
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
enum Status {
Working,
Pausing,
}
impl Display for Status {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Status::Working => write!(f, "working"),
Status::Pausing => write!(f, "pausing"),
}
}
}
impl Pomodoro {
pub fn new(
work: Duration,
pause: Duration,
long_pause: Duration,
pauses_till_long: u64,
) -> Self {
Pomodoro {
work,
pause,
long_pause,
pauses_till_long,
pauses: 0,
status: Status::Working,
timer: Timer::new(Status::Working.to_string().into_boxed_str(), work),
}
}
pub fn handle_expiration(&mut self, notify: bool) {
self.timer.handle_expiration(notify);
let duration = match self.status {
Status::Pausing => self.work,
Status::Working => {
if self.pauses == self.pauses_till_long {
self.long_pause
} else {
self.pause
}
}
};
self.status = match self.status {
Status::Working => {
self.pauses += 1;
Status::Pausing
}
Status::Pausing => Status::Working,
};
self.timer = Timer::new(self.status.to_string().into_boxed_str(), duration);
}
pub fn is_expired(&self) -> bool {
self.timer.is_expired()
}
}