//! 客户端配置

use serde::{Deserialize, Serialize};

/// 客户端配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientConfig {
    /// 服务器地址
    pub server_url: String,
    /// 设备名称
    pub device_name: String,
    /// 质量设置
    pub quality: QualityConfig,
    /// 是否自动启动
    pub auto_start: bool,
    /// 是否开机启动
    pub launch_on_boot: bool,
}

/// 质量配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityConfig {
    /// 帧率
    pub frame_rate: u32,
    /// 分辨率缩放
    pub resolution_scale: f32,
    /// 图像质量 (1-100)
    pub image_quality: u32,
    /// 是否启用硬件加速
    pub hardware_acceleration: bool,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            server_url: "ws://localhost:8080".to_string(),
            device_name: get_default_device_name(),
            quality: QualityConfig::default(),
            auto_start: false,
            launch_on_boot: false,
        }
    }
}

impl Default for QualityConfig {
    fn default() -> Self {
        Self {
            frame_rate: 30,
            resolution_scale: 1.0,
            image_quality: 80,
            hardware_acceleration: true,
        }
    }
}

fn get_default_device_name() -> String {
    hostname::get()
        .map(|h| h.to_string_lossy().to_string())
        .unwrap_or_else(|_| "My Device".to_string())
}

impl ClientConfig {
    /// 从文件加载配置
    pub fn load() -> Self {
        let config_path = Self::config_path();
        if config_path.exists() {
            if let Ok(content) = std::fs::read_to_string(&config_path) {
                if let Ok(config) = serde_json::from_str(&content) {
                    return config;
                }
            }
        }
        Self::default()
    }

    /// 保存配置到文件
    pub fn save(&self) -> anyhow::Result<()> {
        let config_path = Self::config_path();
        if let Some(parent) = config_path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let content = serde_json::to_string_pretty(self)?;
        std::fs::write(config_path, content)?;
        Ok(())
    }

    fn config_path() -> std::path::PathBuf {
        dirs::config_dir()
            .unwrap_or_else(|| std::path::PathBuf::from("."))
            .join("easyremote")
            .join("config.json")
    }
}
