pub mod auth;
pub mod icons;
pub mod navbar;
pub mod topbar;

use crate::{
    util::model::{session::Session, user::User},
    Route,
};
use auth::Auth;
use dioxus::prelude::*;

#[component]
pub fn Global() -> Element {
    let user = use_resource(get_user_from_cookie);

    use_context_provider(|| user);

    rsx! {
        match &*user.read_unchecked() {
            Some(Ok(_)) => rsx! {
                crate::components::layout::topbar::Topbar {}
                main {
                    class: "h-full overflow-y-auto",
                    Outlet::<Route> {}
                }
                crate::components::layout::navbar::Navbar {}
            },
            Some(Err(_)) => rsx! {
                Auth { }
            },
            None => rsx! {
                div { "Loading..." }
            }
        }
    }
}

#[server]
async fn get_user_from_cookie() -> Result<User, ServerFnError> {
    let token = Session::get_token_from_cookie().await?;
    let user = Session::fetch_user_from_token(token).await?;

    Ok(user)
}
