use std::process::Command;

use anyhow::{Context, Result, bail};

use crate::cli::DesktopCommands;

// Grille 2x2 :
//   Web  ↔ Mail
//   Term ↔ Code
// + Others (toggle avec Web)

pub fn run(cmd: &DesktopCommands) -> Result<()> {
    let current = bspc(&["query", "-D", "-d", "--names"])?;

    let target = match cmd {
        DesktopCommands::Left => match current.as_str() {
            "Mail" => "Web",
            "Code" => "Term",
            _ => return Ok(()),
        },
        DesktopCommands::Right => match current.as_str() {
            "Web" => "Mail",
            "Term" => "Code",
            _ => return Ok(()),
        },
        DesktopCommands::Up => match current.as_str() {
            "Term" => "Web",
            "Code" => "Mail",
            _ => return Ok(()),
        },
        DesktopCommands::Down => match current.as_str() {
            "Web" => "Term",
            "Mail" => "Code",
            _ => return Ok(()),
        },
        DesktopCommands::Others => match current.as_str() {
            "Others" => "Web",
            _ => "Others",
        },
    };

    bspc(&["desktop", "-f", target])?;

    Ok(())
}

fn bspc(args: &[&str]) -> Result<String> {
    let output = Command::new("bspc")
        .args(args)
        .output()
        .context("impossible de lancer bspc")?;

    if !output.status.success() {
        bail!("bspc {} a échoué: {}", args.join(" "), String::from_utf8_lossy(&output.stderr));
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
