use rand::rngs::ThreadRng;

use crate::mascot::MascotFrames;
use crate::mascot_fx::{self, DissolveState};
use crate::wizard::state::{StateResult, WizardAction, WizardState};
use crate::wizard::ui_controller::UiController;

pub struct Dissolve {
  tick: usize,
  dissolve_state: DissolveState,
}

impl Dissolve {
  pub fn new(mascot: MascotFrames, rng: &mut ThreadRng) -> Self {
    let dissolve_state = mascot_fx::build_dissolve_state(mascot.lines(), rng);
    Self {
      tick: 0,
      dissolve_state,
    }
  }

  pub fn dissolve_state(&self) -> &DissolveState {
    &self.dissolve_state
  }
}

impl WizardState for Dissolve {
  fn tick(&mut self, ui: &mut UiController, _rng: &mut ThreadRng) -> StateResult {
    let progress = self.tick as f64 / self.dissolve_state.total_ticks as f64;
    ui.mascot.dissolve = progress.min(1.0);

    if self.tick >= self.dissolve_state.total_ticks {
      ui.mascot.dissolve = 1.0;
      return StateResult::Finished;
    }

    self.tick += 1;
    StateResult::Continue
  }

  fn handle_action(&mut self, action: WizardAction, _ui: &mut UiController) -> StateResult {
    match action {
      WizardAction::Exit => StateResult::Finished,
      _ => StateResult::Continue,
    }
  }
}
