//! Simple prompt command implementations

use std::collections::HashMap;
use std::path::PathBuf;
use typedialog_core::prelude::*;

/// Print a single result value in the requested format
pub fn print_result(
    key: &str,
    value: &str,
    format: &str,
    output_file: &Option<PathBuf>,
) -> Result<()> {
    let output = match format {
        "json" => {
            let mut map = HashMap::new();
            map.insert(key, value);
            serde_json::to_string_pretty(&map).unwrap_or_default()
        }
        "yaml" => {
            format!("{}: {}", key, value)
        }
        "toml" => {
            format!("{} = \"{}\"", key, value.escape_default())
        }
        _ => value.to_string(),
    };

    if let Some(path) = output_file {
        std::fs::write(path, &output).map_err(Error::io)?;
    } else {
        println!("{}", output);
    }

    Ok(())
}
