import { _decorator, AudioClip, AudioSource } from 'cc';
import { ConfigKeys, GlobalData } from '../GlobalData';
const { ccclass, property } = _decorator;

// 音效列表
export enum AudioClipNames{
    bgm,
    button_ok,
    start,
    upgrade,
    crash,
    brake,
    win,
    helico,
}

@ccclass('AudioManager')
export class AudioManager {
    private audioSource: AudioSource = null;

    private soundOn: boolean = true

    clips: Map<string, AudioClip> = new Map()

    private static _instance: AudioManager;
    public static get instance () {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new AudioManager();
        return this._instance;
    }

    init(audioSource: AudioSource, allClips:Array<{key:string,clip:AudioClip}>){
        allClips.forEach(item=>{
            this.clips.set(item.key, item.clip)
        })
        this.audioSource = audioSource
        this.getSoundConfig()
        if (this.soundOn){
            this.playBgm(AudioClipNames.bgm)
        }else {
            this.pause()
        }
    }

    getSoundConfig(){
        this.soundOn = GlobalData.instance.getConfigData(ConfigKeys.soundsOn)
        if (this.soundOn === null){
            this.soundOn = true
        }
        return this.soundOn
    }

    setSoundConfig(soundOn: boolean) {
        this.soundOn = soundOn
        if (this.soundOn){
            this.play()
        }else {
            this.pause()
        }
        GlobalData.instance.setConfigData(ConfigKeys.soundsOn, this.soundOn)
    }

    play () {
        if (!this.soundOn) return
        // 播放音乐
        this.audioSource.play();
    }

    pause () {
        // 暂停音乐
        this.audioSource.pause();
    }

    playBgm (clipName: AudioClipNames) {
        if (!this.soundOn) return
        this.audioSource.stop()
        this.audioSource.clip = this.clips.get(AudioClipNames[clipName])
        this.audioSource.play();
    }

    playOneShot (clipName: AudioClipNames, volume: number = 1) {
        if (!this.soundOn) return
        this.audioSource.playOneShot(this.clips.get(AudioClipNames[clipName]), volume);
    }
}
