use std::collections::{HashMap, HashSet};
use std::fs;

use std::result::Result::Ok;
use serde::Deserialize;



#[derive(Deserialize,Clone)]
pub struct LibraryItem {
    pub name: String, 
    pub episodes: String
}


impl LibraryItem {
    pub fn buildfromName(name: &str) -> Result<HashMap<String, Vec<LibraryItem>>, &str> {
        let f = format!("library/{}", name);
        if let Ok(exists)= fs::exists(&f) {
            if exists {
                if let Ok(content)= fs::read_to_string(&f) {
                    let mut data: HashMap<String, Vec<LibraryItem>> = toml::from_str(&content).unwrap();
                    for items in data.values_mut() {
                        let mut hs = HashSet::new();
                        items.retain(|item| {
                            hs.insert(item.name.clone())
                        });
                        items.sort_by(|a,b| {
                            a.name.cmp(&b.name)
                        });
                    }
                    return Ok(data);
                }
            }
        }
        return Err(name); 
    }
}