changxi 0.3.0

TUI EPUB Reader
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::fs;
use std::path::PathBuf;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Config {
    #[serde(default = "default_view_type")]
    pub view_type: String,
    pub border: String,
    pub image_type: String,
}

fn default_view_type() -> String {
    "default".to_string()
}

impl Default for Config {
    fn default() -> Self {
        Self {
            view_type: default_view_type(),
            border: "plain".to_string(),
            image_type: "resize".to_string(),
        }
    }
}

impl Config {
    pub fn load(profile_path: Option<PathBuf>) -> Self {
        let config_path = profile_path.unwrap_or_else(Self::get_default_config_path);

        if let Ok(content) = fs::read_to_string(&config_path) {
            toml::from_str::<_>(&content).unwrap_or_default()
        } else {
            // If file doesn't exist, create it with defaults
            let config = Config::default();
            let _ = Self::save_config(&config, &config_path);
            config
        }
    }

    fn get_default_config_path() -> PathBuf {
        let mut path = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
        path.push("changxi");
        let _ = fs::create_dir_all(&path);
        path.push("config.toml");
        path
    }

    fn save_config(config: &Config, path: &PathBuf) -> Result<(), Box<dyn Error>> {
        let content = toml::to_string_pretty(config)?;
        fs::write(path, content)?;
        Ok(())
    }
}