use std::path::PathBuf;
use std::fs::DirEntry;
use std::ffi::OsStr;
use serde::Serialize;
use rocket::serde::json::Json;
use crate::common::get_clips_dir;

#[derive(Serialize)]
pub struct VideoPreview  {
    name: String,
    thumbnail: Option<String>
}

fn vid_file_entries(path: &OsStr) -> std::io::Result<Vec<DirEntry>> {
    let mut dir = get_clips_dir();
    dir.push('/'); dir.push_str(&path.to_string_lossy());
    let path = std::path::Path::new(&dir);

    if !path.is_dir() {
        panic!("<{:?}> is not a valid directory", path);
    }
    let mut entries: Vec<DirEntry> = Vec::new();
    for ent in path.read_dir()? {
        if let Ok(ent) = ent {
            let name = ent.file_name().into_string().unwrap();
            if name.ends_with("mkv") || name.ends_with("mp4") || name.ends_with("webm") {
                entries.push(ent);
            }
        }
    }
    return Ok(entries);
}


#[get("/category/<cat..>")]
pub fn list(cat: PathBuf) -> Option<Json<Vec<VideoPreview>>> {
    /*
     * List out the videos to a given category
     */
    // First we have to make sure this given category is even registered with us
    let file_path = cat.file_name().unwrap_or(OsStr::new(""));
    if let Ok(entries) = vid_file_entries(file_path) {
        let mut previews: Vec<VideoPreview> = Vec::new();
        // Autismo but at least its bare-able
        for ent in entries {
            let name = ent.file_name(); 
            let name = name.to_string_lossy();

            let cat = cat.to_string_lossy();
            let thumbnail = format!("/thumbnail/{}/{}", cat, name);

            let item = VideoPreview {
                name: name.to_string(),
                thumbnail: Some(thumbnail)
            };
            previews.push(item);
        }
        return Some(Json(previews))
    }
    return None;
}

