use crate::config::Config;
use anyhow::{Context, Result};
use colored::Colorize;
use std::path::Path;

pub fn run(config: &Config, config_path: &Path, subcommand: Option<&str>) -> Result<()> {
    match subcommand.unwrap_or("show").to_lowercase().as_str() {
        "show" => {
            println!("{}", "MPS configuration".white());
            println!("  config file : {}", config_path.display());
            println!("  mps_dir     : {}", config.mps_dir.display());
            println!("  storage_dir : {}", config.storage_dir.display());
            println!("  log_file    : {}", config.log_file.display());
            println!("  git_remote  : {}", config.git_remote);
            println!("  git_branch  : {}", config.git_branch);
            println!("  default_cmd : {}", config.default_command);
            if !config.type_aliases.is_empty() {
                let mut pairs: Vec<String> = config
                    .type_aliases
                    .iter()
                    .map(|(k, v)| format!("{}→{}", k, v))
                    .collect();
                pairs.sort();
                println!("  type_aliases    : {}", pairs.join(", "));
            }
            if !config.command_aliases.is_empty() {
                let mut pairs: Vec<String> = config
                    .command_aliases
                    .iter()
                    .map(|(k, v)| format!("{}→{}", k, v))
                    .collect();
                pairs.sort();
                println!("  command_aliases : {}", pairs.join(", "));
            }
            if !config.custom_tags.is_empty() {
                println!("  custom_tags     : {}", config.custom_tags.join(", "));
            }
            let n = &config.notify;
            println!("  notify.enabled          : {}", n.enabled);
            if let Some(ref t) = n.task_notify_at {
                println!("  notify.task_notify_at   : {}", t);
            }
            println!("  notify.window_minutes   : {}", n.window_minutes);
            println!("  notify.overdue_days     : {}", n.overdue_days);
        }
        "edit" => {
            let editor = std::env::var("EDITOR")
                .or_else(|_| std::env::var("VISUAL"))
                .unwrap_or_else(|_| "vim".to_string());
            println!(
                "{}",
                format!("Opening {} in editor", config_path.display()).white()
            );
            std::process::Command::new(&editor)
                .arg(config_path)
                .status()
                .with_context(|| format!("failed to launch editor '{}'", editor))?;
        }
        other => {
            println!(
                "{}",
                format!("Usage: mps config [show|edit]  (got '{}')", other).yellow()
            );
        }
    }
    Ok(())
}
