use crate::{
    commands::{Cli, Config, Result, edit::edit_client},
    jobber::{JobberCreate, JobberGet},
    print_tip,
    views::ClientView,
};
use clap::Parser;
use color_print::cprintln;
use inquire::Confirm;

/// Create a new client
#[derive(Parser, Debug)]
pub(crate) struct CreateClient {
    /// Client's identifier
    id: String,
}

impl CreateClient {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let config = Config::load()?;
        let mut database = cli.open_database()?;
        loop {
            if !database.create_client(&self.id, edit_client)? {
                cprintln!("Nothing changed.");
                return Ok(());
            }
            println!();
            println!(
                "{}",
                ClientView::from(
                    &self.id,
                    database.get_client(&self.id)?,
                    &config,
                    &database,
                    cli.ansi()
                )?
            );
            println!();
            match Confirm::new("Is this information correct?")
                .with_default(true)
                .with_help_message("cancel create with ESC")
                .prompt_skippable()?
            {
                Some(true) => {
                    cprintln!();
                    cprintln!("Successfully added new client <s>{}</>.", self.id);
                    print_tip!(cli);
                    print_tip!(
                        cli,
                        "Use <s>jobber create job</> to add a job for this client."
                    );
                    print_tip!(cli, "Use <s>jobber show client</> to see the client data.");
                    print_tip!(cli, "Use <s>jobber undo</> to undo the change.");
                    cli.close_database(database)?;
                    return Ok(());
                }
                Some(false) => (),
                None => {
                    cprintln!("Database remained unchanged.");
                    return Ok(());
                }
            }
        }
    }
}
