use crate::{
    commands::{Cli, Config, Result, current_job},
    jobber::JobberIter,
    print_tip,
    views::{JobView, create_job_table},
};
use clap::Parser;
use color_print::cprintln;

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

impl ListJobs {
    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 num_jobs = database.iter_jobs(deleted).count();
        if num_jobs > 0 {
            let current_job = current_job(&config, &database).ok();
            let rows: Vec<_> = database
                .iter_jobs(deleted)
                .map(|(id, _)| JobView::new(id, &config, &database, cli.ansi()))
                .collect::<crate::database::Result<_>>()?;
            let table = create_job_table(rows, &current_job, num_jobs, &config);
            let hours: f64 = database
                .iter_jobs(deleted)
                .map(|(job_id, job)| job.hours(job_id))
                .collect::<crate::entities::Result<Vec<_>>>()?
                .iter()
                .sum();
            cprintln!("{table}");
            cprintln!();
            cprintln!(
                "<s>{num_jobs}</> {deleted_str}job(s) = <s>{:.2} hours</>",
                hours
            );
            print_tip!(cli);
            if self.deleted {
                print_tip!(
                    cli,
                    "Use <s>jobber delete job --restore</> to restore a deleted job."
                );
            }
            print_tip!(cli, "Use <s>jobber show job</> to view a job.");
            print_tip!(cli, "Use <s>jobber select job</> to activate a job.");
            print_tip!(
                cli,
                "Use <s>jobber list job</> to list the current work of a job."
            );
        } else {
            cprintln!("No {deleted_str}jobs.");
            print_tip!(cli);
            print_tip!(cli, "Use <s>jobber create job</> to create one.");
        }
        Ok(())
    }
}
