import { makeAutoObservable } from "mobx"; // 从mobx库导入makeAutoObservable，用于自动观察类的状态变化

import { Howl, Howler } from "howler";
import { watchPageVisibility } from "@src/built-in/page-visibility-notify";

const audioCache = {};

export async function loadAudio(src) {

  if (!audioCache[src]) {
    audioCache[src] = await new Promise((resolve) => {
      let sound = new Howl({
        src,
        preload: true,
        onload: () => {
          resolve(sound);
        },
        onloaderror: () => {
          resolve(null);
        }
      });
    });
  }

  return audioCache[src];
}

let whenHideStatus = false;

// 创建一个音乐存储的类并使用mobx的makeAutoObservable进行自动观察
const musicStore = makeAutoObservable(new class {

  constructor() {
    // 监听页面可见性变化
    watchPageVisibility(this.onPageVisibilityChange);
  }

  // 页面可见性变化的处理函数
  onPageVisibilityChange = async (visible) => {
    if (!visible) {
      whenHideStatus = this.mute;
      this.mute = true;
    } else {
      this.mute = whenHideStatus;
    }
  };

  // 是否静音
  _mute = false;
  get mute() {
    return this._mute;
  }

  set mute(mute) {
    this._mute = mute;
    Howler.mute(mute);
  }

  async playSound(src, loop = false) {
    const howl = await loadAudio(src);
    if (howl) {
      howl.loop(loop);
    }
    howl.play();
  }


});

// 导出音乐存储实例，以便在其他模块使用
export default musicStore;
