/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use crate::{State, request_info::RequestInfo};
use error::MyResult;
use jellycommon::routes::{u_account_login, u_home};
use rocket::{futures::FutureExt, get, response::Redirect};
use std::{future::Future, pin::Pin, sync::Arc};
use tokio::{fs::File, io::AsyncRead};

pub mod account;
pub mod admin;
pub mod assets;
pub mod error;
pub mod home;
pub mod node;
pub mod style;
pub mod player;

#[get("/")]
pub async fn r_index(ri: RequestInfo<'_>) -> MyResult<Redirect> {
    if ri.user.is_some() {
        Ok(Redirect::temporary(u_home()))
    } else {
        Ok(Redirect::temporary(u_account_login()))
    }
}

#[get("/favicon.ico")]
pub async fn r_favicon(s: &rocket::State<Arc<State>>) -> MyResult<File> {
    Ok(File::open(s.config.asset_path.join("favicon.ico")).await?)
}

pub struct Defer(Pin<Box<dyn Future<Output = String> + Send>>);

impl AsyncRead for Defer {
    fn poll_read(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        match self.0.poll_unpin(cx) {
            std::task::Poll::Ready(r) => {
                buf.put_slice(r.as_bytes());
                std::task::Poll::Ready(Ok(()))
            }
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}
