use std::{ops::RangeInclusive, rc::Rc, sync::Arc};

use glam::Vec3;
use sfsm::{State, TransitGuard, Transition};
use winit::keyboard::KeyCode;

use crate::game::{
  anm::{Vm, VmLocation}, GameContext
};

use super::{guard::TimeGuard, title::TitleScreen, UPDATE_CONTEXT};

pub struct Loading {
  sig: Vm,
  ascii_loading: Vm,
  test_snowflakes: Vec<Vm>,
  time: u32,
  range: RangeInclusive<f32>,
  done: TimeGuard,
}

impl Loading {
  pub fn new(context: &mut GameContext) -> Loading {
    let ascii = context.load_anm("ascii.anm");
    let sig_anm = context.load_anm("sig.anm");
    let sig = context.anm_manager.new_vm(sig_anm, None, false, false, 0, VmLocation::new_ui());
    let ascii_loading = context.anm_manager.new_vm(
      ascii.clone(),
      Some(Vec3::new(480.0, 392.0, 0.0)),
      // Some(Vec3::new(300.0, 300.0, 0.0)),
      false,
      false,
      16,
      VmLocation::new_ui(),
    );
    // ascii_loading.borrow_mut().debug_freeze();

    Loading {
      sig,
      ascii_loading,
      test_snowflakes: vec![],
      time: 0,
      range: f32::MAX..=f32::MIN,
      done: TimeGuard::Idle,
    }
    // LoadingState{ascii_loading}
  }
}

impl State for Loading {
  fn execute(&mut self) {
    self.test_snowflakes.retain(|vm| !vm.borrow().deleted());
    self.time += 1;
  }
}

impl Transition<TitleScreen> for Loading {
  fn guard(&self) -> TransitGuard {
    // if self.time > 60 {
    //   TransitGuard::Transit
    // } else {
    //   TransitGuard::Remain
    // }
    UPDATE_CONTEXT.with(|context| context.engine.keys.was_key_pressed(KeyCode::Space)).into()
  }
}
