import LocalStorage from "../Data/LocalStorage";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SoundController extends cc.Component {
  static instance: SoundController;

  private playingSounds: { audio: cc.AudioClip; audioId: number }[] = [];

  @property(Array(cc.AudioClip)) sounds: Array<cc.AudioClip> =
    new Array<cc.AudioClip>();

  protected onLoad(): void {
    SoundController.instance = this;
  }

  public static playLoopSound(sound: cc.AudioClip) {
    if (!LocalStorage.getMusic()) return;
    const audioId = cc.audioEngine.play(sound, true, 1);
    SoundController.instance.playingSounds.push({
      audio: sound,
      audioId: audioId,
    });
  }

  public static playNoLoopSound(sound: cc.AudioClip) {
    if (!LocalStorage.getMusic()) return;
    const audioId = cc.audioEngine.play(sound, false, 1);
    SoundController.instance.playingSounds.push({
      audio: sound,
      audioId: audioId,
    });
  }

  public static stopSound(audioClip: cc.AudioClip) {
    const index = SoundController.instance.playingSounds.findIndex(
      (item) => item.audio === audioClip
    );
    if (index !== -1) {
      const audioId = SoundController.instance.playingSounds[index].audioId;
      cc.audioEngine.stop(audioId);
      SoundController.instance.playingSounds.splice(index, 1);
    }
  }
}
