use thiserror::Error;
use super::calendar::{CalendarDate, DayAvailability};
use crate::{ClientError, InputSource, InputStore};
#[derive(Debug, Default, Clone, Copy)]
pub struct FetchOptions {
pub year: Option<usize>,
pub day: Option<usize>,
pub all: bool,
}
#[derive(Debug)]
pub struct FetchReport {
pub year: usize,
pub day: usize,
pub outcome: Result<InputSource, ClientError>,
}
#[derive(Debug, Error)]
pub enum FetchError {
#[error("Invalid Advent of Code year: {0}")]
InvalidYear(usize),
#[error("Invalid Advent of Code day: {0}")]
InvalidDay(usize),
#[error("--all cannot be combined with --day")]
AllConflict,
#[error("No puzzles are unlocked for {0}")]
NoUnlockedPuzzles(usize),
#[error("Puzzle {year} / Day {day:02} is not unlocked")]
PuzzleLocked { year: usize, day: usize },
#[error(transparent)]
Client(#[from] ClientError),
}
impl FetchOptions {
fn resolve(&self, today: CalendarDate) -> Result<Vec<(usize, usize)>, FetchError> {
if self.all && self.day.is_some() {
return Err(FetchError::AllConflict);
}
let year = self.year.unwrap_or(today.year);
if !(2015..=today.year).contains(&year) {
return Err(FetchError::InvalidYear(year));
}
let unlocked = today.unlocked_days(year);
if let Some(day) = self.day {
match today.day_availability(year, day) {
DayAvailability::OutsideEdition => return Err(FetchError::InvalidDay(day)),
DayAvailability::Locked if unlocked > 0 => {
return Err(FetchError::PuzzleLocked { year, day });
}
DayAvailability::Locked | DayAvailability::Unlocked => {}
}
}
if unlocked == 0 {
return Err(FetchError::NoUnlockedPuzzles(year));
}
if self.all {
return Ok((1..=unlocked).map(|day| (year, day)).collect());
}
Ok(vec![(year, self.day.unwrap_or(unlocked))])
}
}
pub fn execute(options: &FetchOptions) -> Result<Vec<FetchReport>, FetchError> {
let days = options.resolve(CalendarDate::today())?;
let mut store = InputStore::global()?;
let mut reports = Vec::with_capacity(days.len());
for (year, day) in days {
let outcome = store.get_with_source(year, day).map(|(_, source)| source);
let failed = outcome.is_err();
reports.push(FetchReport { year, day, outcome });
if failed {
break;
}
}
Ok(reports)
}
#[cfg(test)]
mod tests;