use crate::command::Command;
use crate::modules::json::Json;
use crate::modules::{
    base58::Base58, base64::Base64, base64url::Base64Url, case::Case, rand::Rand,
};
use clap::{Parser, Subcommand};
use std::{
    io::Write,
    sync::atomic::{AtomicU8, Ordering},
    sync::Mutex,
};

pub static SHOULD_COPY: AtomicU8 = AtomicU8::new(0);

pub static OUTPUT_PATH: Mutex<Option<String>> = Mutex::new(None);

#[derive(Parser)]
pub struct Xb {
    #[clap(long, short, help = "Copy the output to your clipboard")]
    copy: bool,

    #[clap(
        long,
        short,
        help = "Write the output to a file. Creates path if it does not exist"
    )]
    file: Option<String>,

    #[clap(subcommand)]
    commands: Subcommands,
}

#[derive(Subcommand)]
pub enum Subcommands {
    #[clap(about = "Base64 encoder and decoder")]
    Base64(Base64),
    #[clap(name = "base64url", about = "Base64url encoder and decoder")]
    Base64Url(Base64Url),
    #[clap(about = "Base58 encoder and decoder")]
    Base58(Base58),
    #[clap(about = "Random string generator")]
    Rand(Rand),
    #[clap(about = "Change the casing of a string")]
    Case(Case),
    #[clap(about = "Json formatter and validator")]
    Json(Json),
}

impl Command for Xb {
    fn run(&self) -> anyhow::Result<()> {
        if self.copy {
            SHOULD_COPY.fetch_add(1, Ordering::Relaxed);
        }
        if let Some(output_path) = &self.file {
            let mut h = OUTPUT_PATH
                .lock()
                .map_err(|_| anyhow!("Could not acquire lock to output file"))?;
            *h = Some(output_path.to_owned());
        }
        env_logger::builder()
            .filter_level(log::LevelFilter::Info)
            .format(|buf, record| writeln!(buf, "{}", record.args()))
            .init();

        match &self.commands {
            Subcommands::Base64(cmd) => cmd.run(),
            Subcommands::Base64Url(cmd) => cmd.run(),
            Subcommands::Base58(cmd) => cmd.run(),
            Subcommands::Rand(cmd) => cmd.run(),
            Subcommands::Case(cmd) => cmd.run(),
            Subcommands::Json(cmd) => cmd.run(),
        }
    }
}