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

import {loadAudio} from "@/core/preload.ts";
import {watchPageVisibility} from "@/core/page-visibility-notify.ts"; // 导入背景音乐的音频文件

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;
    }
  }

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

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

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


});

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