use crate::{
    commands::{Cli, Config, Result, current_job},
    jobber::{Deleted, JobberGet, JobberIter},
    print_tip,
    views::JobView,
};

use clap::Parser;
use color_print::cprintln;

/// Select a job to work at
///
/// Like start and end together in one command.
///
/// This function can be undone with `jobber undo`.
#[derive(Parser, Debug)]
pub(crate) struct Select {
    /// Job identifier
    job_id: Option<usize>,
}

impl Select {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let mut config = Config::load()?;
        let database = cli.open_database()?;
        let current = current_job(&config, &database)?;
        let job_id = if let Some(job_id) = self.job_id {
            config.set_current_job(job_id);
            cprintln!("Successfully selected job <s>{job_id}</>:");
            job_id
        } else if database.iter_jobs(Deleted::No).count() == 1 && current != 0 {
            config.set_current_job(0);
            cprintln!("Successfully selected the only job.");
            0
        } else {
            let job_id = current;
            cprintln!("Current selected job is <s>{job_id}</>:");
            job_id
        };
        println!();
        println!("{}", JobView::new(job_id, &config, &database, cli.ansi())?);
        let job = database.get_job(job_id)?;
        print_tip!(
            cli,
            "Use <s>jobber start</> to begin work as <s>{}</> for client <s>{}</> in this job.",
            database.get_full_worker_name(&job.worker)?,
            database.get_full_client_name(&job.client)?
        );
        Ok(())
    }
}
