use rocket::{get, routes, Route, State};
use rocket_dyn_templates::{context, Template};
use sqlx::SqlitePool;

use crate::model::{
    stat::{self, BoatStat, Stat},
    user::{DonauLinzUser, UserWithRoles},
};

use super::log::KioskCookie;

#[get("/boats", rank = 2)]
async fn index_boat(db: &State<SqlitePool>, user: DonauLinzUser) -> Template {
    let stat = BoatStat::get(db).await;
    let kiosk = false;

    Template::render(
        "stat.boats",
        context!(loggedin_user: &UserWithRoles::from_user(user.into(), db).await, stat, kiosk),
    )
}

#[get("/boats")]
async fn index_boat_kiosk(db: &State<SqlitePool>, _kiosk: KioskCookie) -> Template {
    let stat = BoatStat::get(db).await;
    let kiosk = true;

    Template::render("stat.boats", context!(stat, kiosk, show_kiosk_header: true))
}

#[get("/?<year>", rank = 2)]
async fn index(db: &State<SqlitePool>, user: DonauLinzUser, year: Option<i32>) -> Template {
    let stat = Stat::people(db, year).await;
    let club_km = Stat::sum_people(db, year).await;
    let guest_km = Stat::guest(db, year).await;
    let personal = stat::get_personal(db, &user).await;
    let kiosk = false;

    Template::render(
        "stat.people",
        context!(loggedin_user: &UserWithRoles::from_user(user.into(), db).await, stat, personal, kiosk, guest_km, club_km),
    )
}

#[get("/?<year>")]
async fn index_kiosk(db: &State<SqlitePool>, _kiosk: KioskCookie, year: Option<i32>) -> Template {
    let stat = Stat::people(db, year).await;
    let club_km = Stat::sum_people(db, year).await;
    let guest_km = Stat::guest(db, year).await;
    let kiosk = true;

    Template::render(
        "stat.people",
        context!(stat, kiosk, show_kiosk_header: true, guest_km, club_km),
    )
}

pub fn routes() -> Vec<Route> {
    routes![index, index_kiosk, index_boat, index_boat_kiosk]
}

#[cfg(test)]
mod test {}
