use std::path::PathBuf;

#[derive(serde::Deserialize, Debug, Clone)]
pub struct FrontMatter {
    pub title: String,
    pub date_created: Option<String>,
    pub date_updated: Option<String>,
    pub index: Option<usize>,
}
#[derive(Debug, Clone)]
pub struct MarkdownModule {
    pub path: PathBuf,
    pub content: String,
    pub metadata: FrontMatter,
}

fn build_markdown_module(markdown_path: &PathBuf) -> Option<MarkdownModule> {
    std::fs::read_to_string(markdown_path).ok().map(|t| {
        match toml_frontmatter::parse::<FrontMatter>(t.as_str()) {
            Ok((fm, md)) => MarkdownModule {
                path: markdown_path.to_owned(),
                content: md.to_string(),
                metadata: fm,
            },
            Err(_) => MarkdownModule {
                path: markdown_path.to_owned(),
                content: t.to_string(),
                metadata: FrontMatter {
                    title: markdown_path
                        .file_stem()
                        .unwrap_or_default()
                        .to_str()
                        .unwrap_or_default()
                        .to_string(),
                    date_created: None,
                    date_updated: None,
                    index: None,
                },
            },
        }
    })
}

pub fn get_markdown_modules(target_path: &PathBuf) -> Vec<MarkdownModule> {
    //if target_path.exists() {}

    let mut mds: Vec<MarkdownModule> = std::fs::read_dir(target_path.clone())
        .expect("could not read target directory")
        .filter_map(|d| {
            println!("found file! {:?}", d);
            d.ok().and_then(|f| build_markdown_module(&f.path()))
        })
        .collect();
    mds.sort_by_key(|e| e.metadata.index);
    mds
    //println!("{:#?}", mds);
    /*for md in mds {
        println!("title: {:?}", md.metadata.title);
        println!("path: {:?}", md.path);
        println!("content: {:?}", md.content);
    }*/

    /*std::fs::read_dir(target_path.clone())
    .unwrap()
    .filter(|x| {
        x.as_ref()
            .unwrap()
            .path()
            .extension()
            .unwrap_or_default()
            .eq("md")
            && !x.as_ref().unwrap().file_name().eq("header.md")
    })
    .map(|x| x.unwrap().path())
    .collect();*/

    /*let test = MarkdownModule {
        path: "".to_owned().into(),
        content: "".to_string(),
        metadata: Some(FrontMatter {
            title: "".to_string(),
            date_created: Some("".to_string()),
            date_updated: Some("".to_string()),
            index: Some(0),
        }),
    };
    vec![test]*/
}
