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

#[derive(Parser, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct ListWorkers {
    /// List only deleted workers
    #[clap(short, long)]
    deleted: bool,
}

impl ListWorkers {
    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_workers(deleted)
            .map(|(id, _)| WorkerView::new(id, &config, &database, cli.ansi()))
            .collect::<Result<_>>()?;
        rows.sort_by_key(|r| r.order.clone());
        let num_workers = database.iter_workers(deleted).count();
        let table = create_worker_table(rows, &config);
        if num_workers > 0 {
            cprintln!("{table}");
            cprintln!();
            cprintln!("<s>{num_workers}</> {deleted_str}worker(s)",);
            print_tip!(cli);
            if self.deleted {
                print_tip!(
                    cli,
                    "Use <s>jobber delete worker --restore</> to restore a deleted worker."
                );
            }
            print_tip!(
                cli,
                "Use <s>jobber create worker</> to create a new worker."
            );
        } else {
            print_tip!(
                cli,
                "No workers.\n\nUse <s>jobber create worker</> to create one."
            );
        }
        Ok(())
    }
}
