import Userdata from "./Userdata";

const { ccclass, property } = cc._decorator;
const SOUND_BASE_PATH = 'audio/';

@ccclass
export default class SoundManager extends cc.Component {
    public static MIN_AUDIO_INTERVAL = 50;

    static lastPlayTimes = {};
    static shootId: number = -1;
    static loadAllAudioClips() {
        cc.loader.loadResDir(SOUND_BASE_PATH);
    }

    private static loadAudioClip(name: string, cb: (audioClip: cc.AudioClip) => void) {
        cc.loader.loadRes(SOUND_BASE_PATH + name, cc.AudioClip, (err, audioClip) => {
            if (err) {
                //cc.error('load audioclip error.', err);
                cb && cb(null);
                return;
            }
            cb && cb(audioClip);
        });
    }

    private static playEffect(name: string, cb?: (clipID: number) => void) {
        if (!Userdata.OpenAudio) {//未开启音效
            return;
        }

        let lastPlayTime = this.lastPlayTimes[name] || 0;

        if (Date.now() - lastPlayTime < this.MIN_AUDIO_INTERVAL) {
            return;
        }
        this.lastPlayTimes[name] = Date.now();

        this.loadAudioClip(name, (audioClip) => {
            if (audioClip) {
                let id = cc.audioEngine.playEffect(audioClip, false);
                cb && cb(id);
            }
        });
    }

    public static playButton() {
        this.playEffect('sound_btn');
    }

    static playStartAudio() {
        this.playEffect('sound_start');
    }
    static playWin() {
        this.playEffect('sound_win');
    }

    static playFailed() {
        this.playEffect('sound_failed');
    }

    static playBall() {
        this.playEffect('sound_ball');
    }

    static playProp() {
        this.playEffect('sound_prop');
    }

    static playStar(num: number) {
        this.playEffect('Star_' + num);
    }
}
