use super::ext::ConfigHandlerExt;
use super::model::Config;
use std::fs;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};

static CONFIG_NAME: &str = "newsflash.json";

#[derive(Debug, Default)]
pub struct ConfigHandler {
    path: Option<PathBuf>,
}

impl ConfigHandlerExt for ConfigHandler {
    fn load(&mut self, config_dir: &Path) -> Result<Config, Error> {
        std::fs::DirBuilder::new().recursive(true).create(config_dir)?;
        let path = config_dir.join(CONFIG_NAME);
        self.path = Some(path.clone());

        if !path.as_path().exists() {
            let config = Config::default();
            self.save(&config)?;
            return Ok(config);
        };

        let data = fs::read_to_string(&path)?;
        let config = serde_json::from_str::<Config>(&data).map_err(|_| Error::new(ErrorKind::InvalidData, "Failed to parse Config"))?;

        Ok(config)
    }

    fn save(&self, config: &Config) -> Result<(), Error> {
        let Some(path) = self.path.as_deref() else {
            return Err(Error::new(ErrorKind::NotFound, "Config not initialized"));
        };

        let data = serde_json::to_string_pretty(config).map_err(|_| Error::new(ErrorKind::InvalidData, "Failed to serialize Config"))?;
        fs::write(path, data)?;
        Ok(())
    }
}
