use clap::{App, Arg, AppSettings};
use dblib::DB;

const DEFAULT_STORAGE: &'static str = "store.json";

fn main() {
    let matches = App::new("clippable-cli")
        .version("0.1")
        .author("shockrah")
        .about("CLI Tool for clippable")
        .setting(AppSettings::ArgRequiredElseHelp)
        .arg(Arg::with_name("generate-key")
             .short("g")
             .long("generate-key")
             .value_name("NAME")
             .help("Generates a new API key to allow usage in this server"))
        .arg(Arg::with_name("remove-key")
             .short("r")
             .long("remove-key")
             .value_name("NAME")
             .help("Removes a key based on the given name"))
        .arg(Arg::with_name("update-key")
             .short("u")
             .long("update-key")
             .value_name("NAME")
             .help("Generate a new key for that user identified by NAME"))
        .arg(Arg::with_name("new-store")
             .short("s")
             .long("new-store")
             .value_name("filename")
             .help("Creates a new file store with the appropriatte structures"))
        .get_matches();

    if let Some(filename) = matches.value_of("new-store") {
        println!("Creating new store {}", filename);
        create_new_store(filename.to_string());
    }

    if let Some(name) = matches.value_of("generate-key") {
        println!("Genating key for {}", name);
        generate_key(String::from(name));
    }

    if let Some(name) = matches.value_of("remove-key") {
        println!("Removing key for {}", name);
        remove_key(String::from(name));
    }

    if let Some(name) = matches.value_of("update-key") {
        println!("Updating key for {}", name);
        update_key(String::from(name));
    }


}

fn create_new_store(filename: String) {
    match DB::new_store(filename) {
        Ok(_) => println!("Store created"),
        Err(e) => eprintln!("Error: {}", e)
    }
}

fn generate_key(name: String) {
    match DB::new_entry(String::from(DEFAULT_STORAGE), name.clone()) {
        Ok(key) => println!("Key for {}\t{}", name, key),
        Err(e) => eprintln!("Error: {}", e)
    }
}

fn remove_key(name: String) {
    match DB::remove_entry(String::from(DEFAULT_STORAGE), name.clone()) {
        Ok(removed) => {
            match removed {
                true => println!("Removed key for {}", name),
                false => println!("Warning: unable to remove key for {}", name)
            };
        },
        Err(e) => eprintln!("Error removing key: {}", e)
    }
}

fn update_key(name: String) {
    remove_key(name.clone());
    generate_key(name);
}

