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

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

impl ListClients {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        cprintln!();
        let database = cli.open_database()?;
        let deleted_str = if self.deleted { "deleted " } else { "" };
        let deleted = self.deleted.into();
        let num_clients = database.iter_clients(deleted).count();
        if num_clients > 0 {
            let config = Config::load()?;
            let mut rows: Vec<_> = database
                .iter_clients(deleted)
                .map(|(id, _)| ClientView::new(id, &config, &database, cli.ansi()))
                .collect::<crate::database::Result<_>>()?;
            rows.sort_by_key(|c| c.order.clone());
            let table = create_client_table(rows, &config);
            cprintln!("{table}\n\n<s>{num_clients}</> {deleted_str}client(s)",);
            print_tip!(cli);
            if self.deleted {
                print_tip!(
                    cli,
                    "Use <s>jobber delete client --restore</> to restore a deleted client."
                );
            }
            print_tip!(cli, "Use <s>jobber show client</> to view a client.");
        } else {
            cprintln!("No {deleted_str}clients.");
            print_tip!(cli,);
            print_tip!(cli, "Use <s>jobber create client</> to create one.");
        }
        Ok(())
    }
}
