use std::fs;
use std::fs::File;
use clap::{App, Arg, ArgMatches, SubCommand};
use rust_util::util_clap::{Command, CommandError};
use crate::util::{JsonKeyPair, make_key_pair};

pub struct CommandImpl;
impl Command for CommandImpl {
    fn name(&self) -> &str { "genkey" }

    fn subcommand<'a>(&self) -> App<'a, 'a> {
        SubCommand::with_name(self.name()).about("Generate key pair subcommand")
        .arg(Arg::with_name("output").long("output").short("o")
            .required(true).takes_value(true).help("Key pair output")
        )
        .arg(Arg::with_name("tag").long("tag").short("t").takes_value(true).help("Key pair output"))
    }

    fn run(&self, _arg_matches: &ArgMatches, sub_arg_matches: &ArgMatches) -> CommandError {
        let output = sub_arg_matches.value_of("output").unwrap();
        let tag = sub_arg_matches.value_of("tag");
        if let Ok(_) = File::open(output) {
            failure!("Output file exists: {}", output);
            return Ok(None);
        }
        let (pri_key, pub_key) = make_key_pair();
        let json_key_pair = JsonKeyPair::from(pri_key, pub_key, tag.map(|t| t.into()));
        success!("Write gen key file: {}", output);
        fs::write(output, json_key_pair.to_json()?.as_bytes())?;
        Ok(None)
    }
}
