use indicatif::ProgressBar;

use crate::{
    action::{Action, StartFields},
    handlers::{Handler, fetch::FetchHandler},
};

pub struct GlobalHandler;

impl Handler for GlobalHandler {
    fn handle(
        &mut self,
        state: &mut crate::state::State,
        action: &crate::action::Action,
    ) -> color_eyre::Result<bool> {
        match action {
            Action::Msg { level, msg } => {
                if *level > 4 {
                    state.println(format!("{level}: {msg}"))?;
                }
                Ok(true)
            }
            Action::Start {
                start_type: StartFields::QueryPathInfo { path, source },
                id,
                ..
            } => {
                let bar = state.add_pb(ProgressBar::new_spinner());
                state.plug(FetchHandler::new(
                    **id,
                    state.term_width,
                    path.clone(),
                    source.clone(),
                    bar,
                ));
                // Handle global start action
                Ok(true)
            }
            _ => Ok(true),
        }
    }
}
