use async_std::fs::read;
use format::BgmFormat;
use rodio::{static_buffer::StaticSamplesBuffer, Sink, Source};

pub mod format;

pub struct BgmManager {
  bgm_format: BgmFormat,
  bgm_file: &'static [u8],
  music_sink: Sink,
}

impl BgmManager {
  pub(super) async fn new(music_sink: Sink) -> BgmManager {
    let bgm_format = BgmFormat::new(read("assets/thbgm.fmt").await.unwrap());
    let bgm_file = read("./thbgm.dat").await.unwrap();
    music_sink.set_volume(0.1);

    Self {
      bgm_format,
      bgm_file: bgm_file.leak(),
      music_sink,
    }
  }

  pub fn play_track(&mut self, file_name: &str) {
    let (intro_range, track_range) = self.bgm_format.get_track_buffers(file_name);
    self.music_sink.clear();

    log::info!("intro: {intro_range:?}, {track_range:?}");

    self.music_sink.append(StaticSamplesBuffer::<i16>::new(
      2,
      44100,
      bytemuck::cast_slice(&self.bgm_file[intro_range]),
    ));

    self.music_sink.append(
      StaticSamplesBuffer::<i16>::new(2, 44100, bytemuck::cast_slice(&self.bgm_file[track_range])).repeat_infinite(),
    );

    self.music_sink.play();
  }
}
