use super::{
    csv_reader::CsvReader,
    dynamic_state::{vato007::ingey::types::HostCsvReaders, DynamicState},
};
use std::collections::HashMap;
use std::fs;
use wasmtime::component::Resource;

pub struct CsvReadersData {
    // Map name of reader to path
    pub readers: HashMap<String, String>,
}

impl HostCsvReaders for DynamicState {
    fn get_reader(
        &mut self,
        self_: Resource<CsvReadersData>,
        name: String,
    ) -> Option<Resource<CsvReader>> {
        let resource = self
            .resources
            .get(&self_)
            .expect("Failed to find own resource");
        let file_path = resource.readers.get(&name);
        if let Some(path) = file_path.cloned() {
            let csv_reader = CsvReader::new(path);
            self.resources.push(csv_reader).ok()
        } else {
            None
        }
    }

    fn drop(&mut self, rep: Resource<CsvReadersData>) -> wasmtime::Result<()> {
        self.resources.delete(rep)?;
        Ok(())
    }

    fn read_into_string(&mut self, self_: Resource<CsvReadersData>, name: String) -> String {
        let resource = self
            .resources
            .get(&self_)
            .expect("Failed to find own resource");
        let file_path = resource.readers.get(&name);
        if let Some(path) = file_path.cloned() {
            let file = fs::read_to_string(path);
            file.unwrap_or(String::new())
        } else {
            String::new()
        }
    }
}
