use std::borrow::Cow;

use indicatif::ProgressBar;
use owo_colors::OwoColorize;

use crate::{action::Action, handlers::Handler, nix_path, util::pad_string};

pub struct FetchHandler {
    id: u64,
    bar: ProgressBar,
    path: String,
    source: String,
}

impl FetchHandler {
    pub fn new<'a>(
        id: u64,
        width: u16,
        path: Cow<'a, str>,
        source: Cow<'a, str>,
        bar: ProgressBar,
    ) -> Self {
        bar.enable_steady_tick(std::time::Duration::from_millis(100));
        let new = Self {
            id,
            bar,
            path: path.to_string(),
            source: source.to_string(),
        };
        new.format(width);
        new
    }
    fn format(&self, width: u16) {
        let name = nix_path::extract_package_name_string(&self.path)
            .expect("Failed to extract package name");
        let chunk = (width - 15) / 2;
        let name = pad_string(&name, chunk as usize);
        let source = pad_string(&self.source, chunk as usize);
        let name = format!("Querying {}", name.green().bold());
        self.bar
            .set_message(format!("{} on {}", name, source.yellow()));
    }
}

impl Handler for FetchHandler {
    fn handle(
        &mut self,
        _state: &mut crate::state::State,
        action: &crate::action::Action,
    ) -> color_eyre::Result<bool> {
        match action {
            &Action::Stop { id, .. } if *id == self.id => {
                self.bar.finish_and_clear();
                Ok(false)
            }
            _ => Ok(true),
        }
    }
    fn on_resize(&mut self, state: &mut crate::state::State) -> color_eyre::Result<()> {
        self.format(state.term_width);
        Ok(())
    }
}
