use crate::{
    commands::{Cli, Result, edit::edit_company},
    jobber::JobberCreate,
    print_tip,
    views::CompanyView,
};
use clap::Parser;
use color_print::cprintln;
use inquire::Confirm;

/// Enter  your company data
#[derive(Parser, Debug)]
pub(crate) struct CreateCompany {}

impl CreateCompany {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let mut database = cli.open_database()?;
        loop {
            if !database.create_company(edit_company)? {
                cprintln!("Nothing changed.");
                return Ok(());
            }
            println!();
            println!("{}", CompanyView::new(&database, cli.ansi())?);
            match Confirm::new("Is this information correct?")
                .with_default(true)
                .with_help_message("cancel create with ESC")
                .prompt_skippable()?
            {
                Some(true) => {
                    cprintln!("Successfully created the company.");
                    print_tip!(cli);
                    print_tip!(
                        cli,
                        "Use <s>jobber show company</> to see the company data."
                    );
                    print_tip!(cli, "Use <s>jobber edit company</> to change company data.");
                    print_tip!(cli, "Use <s>jobber create worker</> to add a worker.");
                    print_tip!(cli, "Use <s>jobber create client</> to add a client.");
                    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(());
                }
            }
        }
    }
}
