use crate::jobber::JobberEdit;
use crate::print_tip;
use crate::{commands::edit::map_empty, entities::Tag};
use crate::{
    commands::{Cli, Result},
    views::TagView,
};
use clap::Parser;
use color_print::cprintln;
use inquire::{Confirm, Text};

/// Edit a tag
#[derive(Parser, Debug)]
pub(crate) struct EditTag {
    /// Name of the tag
    name: String,
}

impl EditTag {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let mut database = cli.open_database()?;
        loop {
            if !database.edit_tag(&self.name, edit_tag)? {
                cprintln!("Nothing changed.");
                return Ok(());
            }
            println!();
            println!("{}", TagView::new(&self.name, &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 edited new tag <s>{}</>.", self.name);
                    print_tip!(cli);
                    print_tip!(
                        cli,
                        "Use <s>jobber start -t {}</> to begin work with this tag.",
                        self.name
                    );
                    print_tip!(cli, "Use <s>jobber show tag</> 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_tag(tag: &mut Tag) -> crate::database::Result<bool> {
    let orig = tag.clone();
    println!();
    println!("Please enter some information about the worker...");
    println!();
    tag.description = map_empty(
        Text::new("Description?")
            .with_default(&orig.description.clone().unwrap_or("-".into()))
            .with_help_message("enter '-' to remove")
            .prompt()?,
    );

    Ok(orig != *tag)
}
