use crate::{
    commands::{Cli, Config, Result, current_job},
    jobber::{JobberGet, JobberWork},
    print_tip,
};
use clap::Parser;
use color_print::cprintln;

/// Sort job's working positions by date/time
///
/// ATTENTION: reassigns all jobs' positions within the database
///
/// This function can be undone with `jobber undo`.
#[derive(Parser, Debug)]
pub(crate) struct Sort {
    /// Job's identifier
    job_id: Option<usize>,
}

impl Sort {
    pub(crate) fn run(&self, cli: &Cli) -> Result<()> {
        let config = Config::load()?;
        let mut database = cli.open_database()?;
        let job_id = self.job_id.unwrap_or(current_job(&config, &database)?);
        database.sort(job_id)?;
        let job = database.get_job(job_id)?;
        let worker = &job.worker.clone();
        let client = &job.client.clone();
        cli.close_database(database)?;
        cprintln!(
            "Successfully sorted work in job <s>{job_id}</> of worker <s>{worker}</> for client <s>{client}</> has been sorted by date/time."
        );
        print_tip!(cli);
        print_tip!(cli, "Use <s>jobber undo</> to undo sorting.");
        Ok(())
    }
}
