1use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5
6use jiff::civil::{Date, Time, Weekday};
7use jiff::{Timestamp, Zoned};
8use vpf::{Day, Plan};
9
10use crate::folder;
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14pub struct Window {
15 pub from: Option<Timestamp>,
17 pub until: Option<Timestamp>,
19}
20
21impl Window {
22 pub fn of(plan: &Plan) -> Self {
24 let read = |text: Option<&str>| text.and_then(|text| text.trim().parse::<Timestamp>().ok());
25 Self {
26 from: read(plan.runs_from()),
27 until: read(plan.runs_until()),
28 }
29 }
30
31 pub fn over(&self, at: Timestamp) -> bool {
33 self.until.is_some_and(|until| at > until)
34 }
35}
36
37fn weekday(day: Day) -> Weekday {
38 match day {
39 Day::Mon => Weekday::Monday,
40 Day::Tue => Weekday::Tuesday,
41 Day::Wed => Weekday::Wednesday,
42 Day::Thu => Weekday::Thursday,
43 Day::Fri => Weekday::Friday,
44 Day::Sat => Weekday::Saturday,
45 Day::Sun => Weekday::Sunday,
46 }
47}
48
49pub fn next_schedule(days: &[Day], dates: &[i64], time: &str, now: &Zoned) -> Zoned {
56 let (hour, minute) = time.split_once(':').expect("a time as HH:MM");
57 let at = Time::new(
58 hour.parse().expect("an hour"),
59 minute.parse().expect("a minute"),
60 0,
61 0,
62 )
63 .expect("a time of day");
64 let wanted: Vec<Weekday> = days.iter().copied().map(weekday).collect();
65 let on_a_date = |date: Date| {
66 let last = i64::from(date.days_in_month());
67 dates
68 .iter()
69 .any(|&wanted| wanted.min(last) == i64::from(date.day()))
70 };
71 (0..=62)
73 .filter_map(|ahead| now.date().checked_add(jiff::Span::new().days(ahead)).ok())
74 .filter(|date| wanted.contains(&date.weekday()) || on_a_date(*date))
75 .filter_map(|date| date.to_datetime(at).to_zoned(now.time_zone().clone()).ok())
76 .find(|start| start > now)
77 .expect("a day within two months")
78}
79
80#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct Snapshot(BTreeMap<PathBuf, u64>);
83
84impl Snapshot {
85 pub fn take(base: &Path, paths: &[String]) -> Self {
87 Self(folder::contents(base, paths))
88 }
89}