use std::{cell::RefCell, ops::RangeInclusive, sync::Arc};

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

use crate::{
  game::{
    anm::{LoadedFile, Vm, VmLocation}, GameContext
  }, utils::soon::Soon
};

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

pub struct Loading {
  _sig: Vm,
  _ascii_loading: Vm,

  title_anm: RefCell<Soon<Arc<LoadedFile>>>,
}

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, 0, VmLocation::new_ui());
    let ascii_loading = context.anm_manager.new_vm(ascii.clone(), None, 16, VmLocation::new_ui());
    ascii_loading.borrow_mut().origin = Vec3::new(480.0, 392.0, 0.0);

    Loading {
      _sig: sig,
      _ascii_loading: ascii_loading,

      title_anm: context.start_load_anm("title.anm").into(),
    }
  }
}

impl State for Loading {
  fn execute(&mut self) {
    // if UPDATE_CONTEXT.with(|context| context.sound_manager.get_bgm_manager().is_some()) {
    //   log::info!("a");
    // }
    // if self.title_anm.borrow_mut().is_done() {
    //   log::info!("b")
    // }
  }
}

impl Transition<TitleScreen> for Loading {
  fn guard(&self) -> TransitGuard {
    UPDATE_CONTEXT
      .with(|context| context.sound_manager.is_bgm_manager_loaded() && self.title_anm.borrow_mut().is_done())
      .into()
  }
}
