use std::env;
use seahorse::{App,Context,Flag,FlagType};
use deckster::{generate_sample,start_tui};
use deckster::errors::Res;

fn main() {
    let args: Vec<String> = env::args().collect();

    let file_flag = Flag::new("file",FlagType::String)
        .description("toml file containing cards.")
        .alias("f");

    let num_flag = Flag::new("num", FlagType::Int)
        .description("number of cards to be studied ( optional )")
        .alias("n");

    let sample_flag = Flag::new("sample",FlagType::Bool)
        .description("prints a sample toml file to stdout.")
        .alias("s");

    let app = App::new(env!("CARGO_PKG_NAME"))
        .description(DESCRIPTION)
        .author(env!("CARGO_PKG_AUTHORS"))
        .version(env!("CARGO_PKG_VERSION"))
        .usage("deckster [flag] [arg]")
        .action(deckster)
        .flag(file_flag)
        .flag(num_flag)
        .flag(sample_flag);

    app.run(args);
}

fn deckster(c: &Context) {
    if  c.bool_flag("sample") { generate_sample().unwrap() }
    else { run_app(c).unwrap() }
}

fn run_app(c: &Context) -> Res<()> {
    let file = if let Ok(file) = c.string_flag("file") { file }
    else { c.help(); return Ok(()) };

    let num = if let Ok(n) = c.int_flag("num") { Some(n as usize)}
    else { None };

    // TODO : handle errors
    start_tui(&file,num)?;
    Ok(())
}

const DESCRIPTION: &str = r#"
    Tui interface to study flashcards in the terminal. Inspired by
    Anki and uses a modified sm-2 algorithm.

    Cards are stored in a toml file following a specific format.
    See flag -s / --sample below.

    Only text is supported. Users could add urls to Q/A fields
    and use their terminal to grab them and open multimedia content.

    Keybindings
    -----------
    SPACE   :   Reveal answer. When pressed again reveals rating options.
    RETURN  :   Submit rating and move to the next card.
    l/RIGHT :   Select next rating option.
    h/LEFT  :   Select previous rating option.
    q/ESC   :   Exit application.
"#;
