use std::fs;
use std::path::Path;
use crate::models::picture::Picture;
use std::collections::HashSet;

#[derive(Debug, Clone, PartialEq)]
pub struct FileSystemReader {

}

impl FileSystemReader {
    pub fn new() -> Self {
        FileSystemReader {}
    }

    pub fn list_resources_in_dir(path: &Path) -> HashSet<Picture> {
        let mut entries = HashSet::new();
        if path.is_dir() {
            entries = fs::read_dir(path)
                .map(|res| res.map(|ent| {
                    Picture::new(ent.unwrap())
                }).collect::<HashSet<Picture>>())
                .unwrap();
        };
        entries
    }

    pub fn list_files_in_dir(&self, path: &Path) -> HashSet<Picture> {
        let mut entries: HashSet<Picture> = HashSet::new();
        if path.is_dir() {
            entries = fs::read_dir(path)
                .map(|res| res.map(|ent| {
                    let entry = ent.unwrap();
                    let new_path = entry.path();
                    if new_path.is_dir() {
                        FileSystemReader::list_files_in_dir(&self, &new_path)
                    } else {
                        let mut files: HashSet<Picture> = HashSet::new();
                        files.insert(Picture::new(entry));
                        files
                    }
                })
                    .flat_map(|file_list| file_list)
                    .collect::<HashSet<Picture>>())
                .unwrap();
        };
        entries
    }

    pub fn list_pictures_in_files(&self, files: HashSet<Picture>) -> HashSet<Picture> {
        files.into_iter()
            .filter(|file| file.media_type != None)
            .collect::<HashSet<Picture>>()
    }

    pub fn file_exists(&self, file: &Picture) -> bool {
        Path::new(file.path.as_str()).exists()
    }
}
