use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use jiff::civil::{Date, Time, Weekday};
use jiff::{Timestamp, Zoned};
use vpf::{Day, Plan};
use crate::folder;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Window {
pub from: Option<Timestamp>,
pub until: Option<Timestamp>,
}
impl Window {
pub fn of(plan: &Plan) -> Self {
let read = |text: Option<&str>| text.and_then(|text| text.trim().parse::<Timestamp>().ok());
Self {
from: read(plan.runs_from()),
until: read(plan.runs_until()),
}
}
pub fn over(&self, at: Timestamp) -> bool {
self.until.is_some_and(|until| at > until)
}
}
fn weekday(day: Day) -> Weekday {
match day {
Day::Mon => Weekday::Monday,
Day::Tue => Weekday::Tuesday,
Day::Wed => Weekday::Wednesday,
Day::Thu => Weekday::Thursday,
Day::Fri => Weekday::Friday,
Day::Sat => Weekday::Saturday,
Day::Sun => Weekday::Sunday,
}
}
pub fn next_schedule(days: &[Day], dates: &[i64], time: &str, now: &Zoned) -> Zoned {
let (hour, minute) = time.split_once(':').expect("a time as HH:MM");
let at = Time::new(
hour.parse().expect("an hour"),
minute.parse().expect("a minute"),
0,
0,
)
.expect("a time of day");
let wanted: Vec<Weekday> = days.iter().copied().map(weekday).collect();
let on_a_date = |date: Date| {
let last = i64::from(date.days_in_month());
dates
.iter()
.any(|&wanted| wanted.min(last) == i64::from(date.day()))
};
(0..=62)
.filter_map(|ahead| now.date().checked_add(jiff::Span::new().days(ahead)).ok())
.filter(|date| wanted.contains(&date.weekday()) || on_a_date(*date))
.filter_map(|date| date.to_datetime(at).to_zoned(now.time_zone().clone()).ok())
.find(|start| start > now)
.expect("a day within two months")
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Snapshot(BTreeMap<PathBuf, u64>);
impl Snapshot {
pub fn take(base: &Path, paths: &[String]) -> Self {
Self(folder::contents(base, paths))
}
}