use askama::Template;
use time::Date;

use crate::sources;

#[derive(Template)]
#[template(path = "index.html")]
pub struct HomeTemplate {
    time_since: TimeSince,
}

pub struct TimeSince {
    days: i32,
}

impl TimeSince {
    fn from_interval(leak: &Date, now: &Date) -> Self {
        Self {
            days: now.to_julian_day() - leak.to_julian_day(),
        }
    }
}

#[axum::debug_handler]
pub async fn get() -> HomeTemplate {
    let mut t = vec![];

    for source in sources::sources() {
        let url = source.url();
        let Ok(res) = (reqwest::get(url)).await else {
            tracing::error!("fetch error");
            continue;
        };

        let Ok(text) = res.text().await else {
            tracing::error!("fetch decode text error");
            continue;
        };

        let Ok(last) = source.latest_leak(text) else {
            tracing::error!("source decode error");
            continue;
        };

        t.push(last);
    }

    let last = t
        .into_iter()
        .max()
        .unwrap_or(time::Date::from_calendar_date(2021, time::Month::July, 14).unwrap());

    let now = time::OffsetDateTime::now_utc();
    let now = time::Date::from_calendar_date(now.year(), now.month(), now.day()).unwrap();

    HomeTemplate {
        time_since: TimeSince::from_interval(&last, &now),
    }
}
