use crate::command::Command;

#[derive(Debug, clap::Args)]
#[clap(name = "command")]
pub struct Base58 {
    #[clap(flatten)]
    group: Group,
}

#[derive(Debug, clap::Args)]
#[group(required = true, multiple = false)]
pub struct Group {
    #[arg(long, short, help = "String to encode")]
    pub encode: Option<String>,
    #[arg(long, short, help = "String to decode")]
    pub decode: Option<String>,
}

impl Command for Base58 {
    fn run(&self) -> anyhow::Result<()> {
        if let Some(input) = &self.group.encode {
            out!("{}", Base58::encode(input.to_owned())?);
        }

        if let Some(input) = &self.group.decode {
            out!("{}", Base58::decode(input.to_owned())?);
        }

        Ok(())
    }
}

impl Base58 {
    pub fn encode<T: AsRef<[u8]>>(input: T) -> anyhow::Result<String> {
        Ok(bs58::encode(input).into_string())
    }

    pub fn decode<T: AsRef<[u8]>>(input: T) -> anyhow::Result<String> {
        String::from_utf8(
            bs58::decode(input)
                .into_vec()
                .map_err(|_| anyhow!("Unable to decode input"))?,
        )
        .map_err(|_| anyhow!("Unable to convert base58 output to string"))
    }
}