use crate::{command::Command, stdin::str_or_stdin};

#[derive(Debug, clap::Args)]
#[clap(name = "command")]
pub struct Json {
    #[clap(short, long, help = "JSON input")]
    input: Option<String>,
    #[clap(short, long, help = "Validate the JSON", conflicts_with = "validate")]
    format: bool,
    #[clap(short, long, help = "Format the JSON", conflicts_with = "format")]
    validate: bool,
}

impl Command for Json {
    fn run(&self) -> anyhow::Result<()> {
        let s = str_or_stdin(self.input.clone());
        if self.validate {
            if let Err(e) = Json::validate(&s) {
                out!("{}", e.to_string());
            } else {
                out!("JSON is valid");
            }
        } else {
            out!("{}", Json::format(&s)?);
        }

        Ok(())
    }
}

impl Json {
    pub fn validate(input: &str) -> anyhow::Result<()> {
        serde_json::from_str::<serde_json::Value>(input)
            .map_err(|e| anyhow!("Invalid JSON. {}", e.to_string()))?;

        Ok(())
    }

    pub fn format(input: &str) -> anyhow::Result<String> {
        let j: serde_json::Value =
            serde_json::from_str(input).map_err(|e| anyhow!("Invalid JSON. {}", e.to_string()))?;
        let s = serde_json::to_string_pretty(&j)?;

        Ok(s)
    }
}