use super::{Job, UiSender};

/// Klavye düzenini /etc/vconsole.conf, /etc/conf.d/mudur ve X11 yapılandırmasına yazar.
pub struct ConfigureKeyboardJob {
    pub mount:    String,
    pub layout:   String,  // ör. "tr"
    pub variant:  String,  // ör. "f" veya ""
    pub language: String,  // ör. "tr", "de", "fr"
}

#[async_trait::async_trait]
impl Job for ConfigureKeyboardJob {
    fn name(&self) -> &str { "job_keyboard" }

    async fn run(&self, ui: &UiSender) -> Result<(), String> {
        // Konsol (TTY) keymap adı: X11 layout'undan farklı olabilir.
        // Türkçe'de masaüstü "tr" çalışır ama vconsole keymap'i "trq" (Q) / "trf" (F) olmalı;
        // "tr" değeri kbd'de hata verir.
        let keymap = match (self.layout.as_str(), self.variant.as_str()) {
            ("tr", "") => "trq".to_string(),
            ("tr", "f") => "trf".to_string(),
            _ => {
                if self.variant.is_empty() {
                    self.layout.clone()
                } else {
                    format!("{}-{}", self.layout, self.variant)
                }
            }
        };

        // /etc/vconsole.conf  (systemd-style TTY)
        let vconsole_path = format!("{}/etc/vconsole.conf", self.mount);
        let vconsole = format!("KEYMAP={}\nFONT=ter-v16n\n", keymap);
        ui.log(format!("Yazılıyor: {}", vconsole_path));
        let _ = tokio::fs::write(&vconsole_path, vconsole).await;

        // /etc/conf.d/mudur  (PisiLinux native init)
        let mudur_dir  = format!("{}/etc/conf.d", self.mount);
        let mudur_path = format!("{}/mudur", mudur_dir);
        tokio::fs::create_dir_all(&mudur_dir).await
            .map_err(|e| format!("{} oluşturulamadı: {}", mudur_dir, e))?;

        let content = tokio::fs::read_to_string(&mudur_path).await.unwrap_or_default();
        let mut lines: Vec<String> = content.lines().map(String::from).collect();
        let mut found_keymap   = false;
        let mut found_language = false;

        for line in lines.iter_mut() {
            let trimmed = line.trim();
            if trimmed.starts_with("keymap=") || trimmed.starts_with("#keymap=") {
                *line = format!("keymap=\"{}\"", keymap);
                found_keymap = true;
            } else if trimmed.starts_with("language=") || trimmed.starts_with("#language=") {
                *line = format!("language=\"{}\"", self.language);
                found_language = true;
            }
        }

        if !found_keymap {
            lines.push(format!("keymap=\"{}\"", keymap));
        }
        if !found_language {
            lines.push(format!("language=\"{}\"", self.language));
        }

        let result = lines.join("\n");
        ui.log(format!("Yazılıyor: {}", mudur_path));
        tokio::fs::write(&mudur_path, result).await
            .map_err(|e| format!("{} yazılamadı: {}", mudur_path, e))?;

        // /etc/X11/xorg.conf.d/00-keyboard.conf  (X11 için)
        let x11_dir  = format!("{}/etc/X11/xorg.conf.d", self.mount);
        let x11_path = format!("{}/00-keyboard.conf", x11_dir);
        tokio::fs::create_dir_all(&x11_dir).await
            .map_err(|e| format!("{} oluşturulamadı: {}", x11_dir, e))?;

        let options_line = if self.variant.is_empty() {
            String::new()
        } else {
            format!("\n\t\tOption \"XkbVariant\" \"{}\"", self.variant)
        };

        let x11_conf = format!(
            "Section \"InputClass\"\n\
             \tIdentifier \"system-keyboard\"\n\
             \tMatchIsKeyboard \"on\"\n\
             \tOption \"XkbLayout\" \"{layout}\"{options}\n\
             EndSection\n",
            layout  = self.layout,
            options = options_line,
        );
        ui.log(format!("Yazılıyor: {}", x11_path));
        tokio::fs::write(&x11_path, x11_conf)
            .await
            .map_err(|e| format!("xorg keyboard conf yazılamadı: {}", e))?;

        Ok(())
    }
}
