use crate::{
    commands::{Cli, Config, Result, edit::obligatory},
    entities::Worker,
    jobber::JobberEdit,
    print_tip,
    views::WorkerView,
};
use clap::Parser;
use color_print::cprintln;
use inquire::{Confirm, Text};

/// Edit a worker.
#[derive(Parser, Debug)]
pub(crate) struct EditWorker {
    /// Worker's identifier
    id: String,
}

impl EditWorker {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let config = Config::load()?;
        let mut database = cli.open_database()?;
        loop {
            if !database.edit_worker(&self.id, edit_worker)? {
                cprintln!("Nothing changed.");
                return Ok(());
            }
            println!();
            println!(
                "{}",
                WorkerView::new(&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 worker.");
                    print_tip!(cli);
                    print_tip!(cli, "Use <s>jobber show worker</> to see the worker 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_worker(worker: &mut Worker) -> crate::database::Result<bool> {
    let orig = worker.clone();
    println!();
    println!("Please enter some information about the worker...");
    println!();
    worker.full_name = Text::new("Worker's Full Name?")
        .with_validator(obligatory)
        .with_default(&orig.full_name)
        .prompt()?;

    Ok(orig != *worker)
}
