use radicle_ci_broker::{ergo, pages::StatusPage, worker::start_thread};

use super::*;

/// Produce HTML reports based on database contents.
#[derive(Parser)]
pub struct ReportCmd {
    /// Write HTML files to this directory. The directory must exist:
    /// it is not created automatically.
    #[clap(long)]
    output_dir: PathBuf,

    /// HTML snippet to be inserted at top of generated front page,
    /// for describing the CI node instance.
    #[clap(long)]
    description: Option<String>,

    /// Default refresh interval for generated HTML page.
    #[clap(long, default_value = "86400")]
    refresh_interval: usize,
}

impl Leaf for ReportCmd {
    fn run(&self, args: &Args) -> Result<(), CibToolError> {
        let db = args.open_db()?;

        let mut run_notification = NotificationChannel::new_run();
        let mut page = StatusPage::new(
            run_notification.rx().map_err(CibToolError::Notification)?,
            ergo::Radicle::new().map_err(CibToolError::Ergo)?,
            db,
            true,
            self.refresh_interval,
        );
        if let Some(desc) = &self.description {
            page.set_description(desc);
        }
        page.set_output_dir(&self.output_dir);

        let thread = start_thread(page);
        thread.join().unwrap()?;

        Ok(())
    }
}
