use super::*;
use std::collections::hash_map::HashMap;

pub type FileSystemMap = HashMap<String, SharedPtr<File>>;

pub fn new_file_map(root: &Directory) -> FileSystemMap {
    fn add_files(file_system: &mut FileSystemMap, dir: &Directory, mut parent: String) {
        if !dir.name.is_root() {
            if let Some(dir_name) = dir.name.as_string() {
                if !dir_name.is_empty() {
                    parent.push_str(dir_name.as_ref());
                    parent.push('/');
                }
            }
        }

        for file in &dir.files {
            if let Some(name) = file.borrow().name.as_string() {
                let path = {
                    let mut path = parent.clone();
                    
                    path.push_str(name.as_ref());
                    path
                };
                
                file_system.insert(path, file.clone());
            }
        }

        for dir in &dir.dirs {
            add_files(file_system, &dir.borrow(), parent.clone());
        }
    }

    let mut file_system = HashMap::new();

    add_files(&mut file_system, root, "".to_owned());
    file_system
}