use actix_web::{get, HttpRequest, Responder};

#[get("/icon")]
pub async fn icon_resource(_r: HttpRequest) -> impl Responder {
    web_base::send_data(
        include_bytes!("../icon.png").to_vec(),
        "image/png",
        "icon.png",
    )
}

#[get("/video/raw")]
pub async fn video_file(r: HttpRequest) -> Option<impl Responder> {
    let library: &actix_web::web::Data<crate::library::Library> = r.app_data().unwrap();
    let query = web_base::parse_query_string(r.query_string());
    if let Some(video_id) = query.get("v") {
        let (_, mut video) = if let Some((channel, video)) = library.get_video_by_hash(video_id) {
            (channel, video)
        } else {
            library.get_video_by_youtube_id(video_id).unwrap()
        };
        return Some(actix_files::NamedFile::open(video.path().unwrap()).unwrap());
    }
    None
}

#[get("/video/thumbnail")]
pub async fn video_thumbnail(r: HttpRequest) -> Option<impl Responder> {
    let library: &actix_web::web::Data<crate::library::Library> = r.app_data().unwrap();
    let query = web_base::parse_query_string(r.query_string());
    if let Some(video_id) = query.get("v") {
        let (_, mut video) = if let Some((channel, video)) = library.get_video_by_hash(video_id) {
            (channel, video)
        } else {
            library.get_video_by_youtube_id(video_id).unwrap()
        };
        let path = video.path().unwrap();
        let parent = path.parent().unwrap();
        let thumbnail_path = path.file_stem().unwrap().to_str().unwrap();
        let thumbnail_path = parent.join(thumbnail_path);
        let thumbnail_path = thumbnail_path.to_str().unwrap();
        return Some(actix_files::NamedFile::open(format!("{thumbnail_path}.jpg")).unwrap());
    }
    None
}
