use crate::{
    commands::{Cli, Config, Result},
    jobber::JobberIter,
    print_tip,
    views::{TagView, create_tag_table},
};
use clap::Parser;
use color_print::cprintln;

#[derive(Parser, Debug)]
pub(crate) struct ListTags {
    /// List only deleted tags
    #[clap(short, long)]
    deleted: bool,
}

impl ListTags {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        cprintln!();
        let config = Config::load()?;
        let database = cli.open_database()?;
        let deleted_str = if self.deleted { "deleted " } else { "" };
        let deleted = self.deleted.into();
        let mut rows: Vec<_> = database
            .iter_tags(deleted)
            .map(|(id, _)| TagView::new(id, &database, cli.ansi()))
            .collect::<crate::database::Result<_>>()?;
        rows.sort_by_key(|r| r.name.clone());
        let num_tags = database.iter_tags(deleted).count();
        if num_tags > 0 {
            let table = create_tag_table(rows, &config);
            cprintln!("{table}");
            cprintln!();
            cprintln!("<s>{num_tags}</> {deleted_str}tags(s)",);
            print_tip!(cli);
            if self.deleted {
                print_tip!(
                    cli,
                    "Use <s>jobber delete tag --restore</> to restore a deleted tag."
                );
            }
            print_tip!(cli, "Use <s>jobber show tag</> to view tag details.");
        } else {
            cprintln!("No tags defined.");
            print_tip!(cli);
            print_tip!(cli, "Use <s>jobber create tag</> to create some.");
        }
        Ok(())
    }
}
