use std::path::PathBuf;
use std::{collections::BTreeMap, path::Path};
use std::io;
pub struct CaseList {
    index_map: BTreeMap<usize, String>,
    base_path: PathBuf
}

impl CaseList {
    pub fn from_dir(dir: &Path) -> io::Result<Self> {
        let mut index_map = BTreeMap::new();
        let case_dir = std::fs::read_dir(dir)?;
        for case_item in case_dir {
            let case_item = case_item?;
            let file_name = match case_item.file_name().into_string() {
                Ok(name) => name,
                Err(_) => continue, // skip non-utf8 file names
            };
            if file_name.ends_with(".c") {
                if let Some((index_str, _)) = file_name.split_once('_') {

                    if let Ok(index) = index_str.parse::<usize>() {
                        index_map.insert(index, file_name);
                    }
                }
            }
        }
        Ok(Self { index_map, base_path: dir.to_path_buf() })
    }

    pub fn get_case_name(&self, index: usize) -> Option<&String> {
        self.index_map.get(&index)
    }

    pub fn get_case_path(&self, index: usize) -> Option<PathBuf> {
        self.get_case_name(index).map(|name| self.base_path.join(name))
    }
}