use crate::{
    commands::{
        Cli, Config, Result,
        edit::{edit_address::edit_address, edit_scheme::edit_scheme, map_empty},
    },
    entities::Client,
    jobber::{JobberEdit, JobberGet},
    print_tip,
    views::ClientView,
};
use clap::Parser;
use color_print::cprintln;
use inquire::{Confirm, Text};

/// Edit client's address
#[derive(Parser, Debug)]
pub(crate) struct EditClient {
    /// Client's identifier
    id: String,
}

impl EditClient {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let config = Config::load()?;
        let mut database = cli.open_database()?;
        loop {
            if !database.edit_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()
                )?
            );
            match Confirm::new("Is this information correct?")
                .with_default(true)
                .with_help_message("cancel change with ESC")
                .prompt_skippable()?
            {
                Some(true) => {
                    cprintln!("Successfully edited client {}.", self.id);
                    print_tip!(cli);
                    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(());
                }
            }
        }
    }
}

pub(crate) fn edit_client(client: &mut Client) -> crate::database::Result<bool> {
    let orig = client.clone();

    edit_address(&mut client.address)?;

    println!();
    println!("Add tax information...");
    println!();
    client.vat = map_empty(
        Text::new("Tax No. (VAT)?")
            .with_default(&orig.vat.clone().unwrap_or("-".into()))
            .with_help_message("enter '-' to remove")
            .prompt()?,
    );

    edit_scheme(&mut client.scheme)?;

    Ok(orig != *client)
}
