use std::{path::Path, sync::Arc};

use async_std::fs;
use wgpu::{Device, Queue};
use winit::{dpi::PhysicalSize, window::Window};

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

use super::Manager;

impl Manager {
  pub fn start_load_anm(
    &mut self,
    device: Arc<Device>,
    queue: Arc<Queue>,
    size: Option<PhysicalSize<u32>>,
    file_name: impl AsRef<Path>,
  ) -> Soon<Arc<LoadedFile>> {
    let file_name_str = file_name.as_ref().to_str().unwrap().to_owned();
    if let Some(loaded_anm) = self.anm_files.get(&file_name_str) {
      return Soon::Value(loaded_anm.clone());
    }

    let file_name = file_name.as_ref().to_owned();
    Soon::new(async move {
      let file_data = fs::read(Path::new("./assets").join(file_name)).await.expect("failed to load anm file");
      let file = Arc::new(LoadedFile::load(&device, &queue, size, &file_name_str, &file_data));

      file
    })
  }

  pub fn load_anm(
    &mut self,
    device: &Device,
    queue: &Queue,
    window: &Window,
    file_name: impl AsRef<Path>,
  ) -> Arc<LoadedFile> {
    let file_name_str = file_name.as_ref().to_str().unwrap().to_owned();
    if let Some(loaded_anm) = self.anm_files.get(&file_name_str) {
      return loaded_anm.clone();
    }

    let file_data = std::fs::read(Path::new("./assets").join(file_name)).expect("failed to load anm file");
    let loaded_anm = Arc::new(LoadedFile::load(
      device,
      queue,
      Some(window.inner_size()),
      &file_name_str,
      &file_data,
    ));

    self.anm_files.insert(file_name_str.to_owned(), loaded_anm.clone());
    loaded_anm
  }
}
