use crate::{
    commands::{Cli, Config, Result, current_job},
    jobber::JobberGet,
    print_tip,
    views::{JobView, WorkView, create_work_table},
};
use clap::Parser;

#[derive(Parser, Debug)]
pub(crate) struct ShowJob {
    /// Job's identifier
    job_id: Option<usize>,
    /// Show list of work positions
    #[clap(long, short)]
    worked: bool,
}

impl ShowJob {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        println!();
        let config = Config::load()?;
        let database = cli.open_database()?;
        let job_id = if let Some(id) = self.job_id {
            id
        } else {
            current_job(&config, &database)?
        };
        let current_job = current_job(&config, &database).ok();
        let job = database.get_job(job_id)?;
        print!("{}", JobView::new(job_id, &config, &database, cli.ansi())?);
        if self.worked {
            let scheme = &job.scheme(job_id)?;
            if job.work.is_empty() {
                println!("There is no done work in job {job_id}");
                return Ok(());
            }
            let mut rows: Vec<_> = job
                .work
                .iter()
                .enumerate()
                .map(|(n, w)| WorkView::new(Some(n), w, database.get_tags(), scheme, cli.ansi()))
                .collect();
            rows.sort_by_key(|r| r.order);
            if let Some(running) = &job.running {
                rows.push(WorkView::new_running(running, scheme, cli.ansi()));
            }
            println!("{}", create_work_table(rows, &config));
        }
        print_tip!(cli,);
        print_tip!(
            cli,
            "Use <s>jobber start{}</> to begin work within this job.",
            if current_job == Some(job_id) {
                String::new()
            } else {
                format!(" -j {job_id}")
            }
        );
        Ok(())
    }
}
