jana_sessions_webpage/src/lib.rs

115 lines
2.4 KiB
Rust

use crate::session_date_calculator::{Day, NthWeekday};
use chrono::{NaiveDate, Weekday};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub mod session_date_calculator;
pub mod webpage;
#[derive(Debug, Clone)]
pub struct DatedSession {
pub day: Day,
pub session: Session,
pub applying_exception: Option<Exception>,
}
impl Noted for DatedSession {
fn note(&self) -> Option<&String> {
match &self.applying_exception {
Some(e) => e.note(),
None => self.session.note(),
}
}
}
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum Session {
Regular {
rule: NthWeekday,
note: Option<String>,
except: HashMap<NaiveDate, Exception>,
},
Extra {
date: NaiveDate,
note: Option<String>,
},
}
impl Session {
pub fn into_dated(self, day: Day) -> Result<DatedSession, Self> {
if !self.is_applicable_to(&day) {
return Err(self);
}
let dated_session = DatedSession {
applying_exception: match self {
Session::Regular { ref except, .. } => except.get(&day.date).cloned(),
_ => None,
},
session: self,
day,
};
Ok(dated_session)
}
pub fn is_applicable_to(&self, day: &Day) -> bool {
match *self {
Session::Regular { rule, .. } => rule.matches(day),
Session::Extra { date, .. } => day.date == date,
}
}
}
impl Noted for Session {
fn note(&self) -> Option<&String> {
match self {
Session::Regular { note, .. } => note,
Session::Extra { note, .. } => note,
}
.as_ref()
}
}
#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum Exception {
Cancel {
note: Option<String>,
},
Alter {
#[serde(default)]
date: Option<NaiveDate>,
#[serde(default)]
note: Option<String>,
},
}
impl Noted for Exception {
fn note(&self) -> Option<&String> {
match self {
Exception::Cancel { note, .. } => note,
Exception::Alter { note, .. } => note,
}
.as_ref()
}
}
pub trait Noted {
fn note(&self) -> Option<&String>;
}
pub fn localize_day(day: &Day) -> String {
format!(
"{}, {}",
match day.weekday {
Weekday::Mon => "Montag",
Weekday::Tue => "Dienstag",
Weekday::Wed => "Mittwoch",
Weekday::Thu => "Donnerstag",
Weekday::Fri => "Freitag",
Weekday::Sat => "Samstag",
Weekday::Sun => "Sonntag",
},
day.date.format("%d.%m.%Y")
)
}