import StartScene1 from "../startScene/StartScene";

let soundOn = true;
let bgChannel: egret.SoundChannel;
let loading = false;
let soundArr = [];
export const getSoundOn = () => {
    return soundOn
}

export const toggleSound = () => {
    soundOn = !soundOn;
    if (bgChannel) {
        if (!soundOn) {
            bgChannel.stop();
            bgChannel = null;
        }
    } else {
        if (soundOn) {
            playBg();
        }
    }
}

export const playBg = async () => {
    if (bgChannel) return;
    if (loading) return;
    loading = true;
    const bg = await RES.getResAsync('bgMusic_mp3');
    bgChannel = bg.play();
    loading = false;
}

export enum SoundType {
    click = 'click',
    bounce = 'bounce',
    good = 'good',
    recover = 'recover',
    shoot = 'shoot',
}

export const playSound = async (type: any) => {
    if (!soundOn) return;
    if (!StartScene1.isPlayMusic) return;
    for(let i = 0; i < soundArr.length; i ++){
        soundArr[i].stop();
    }
    let sound: egret.Sound = RES.getRes(type + "_mp3");
    if (sound){
        let chanel = sound.play(0, 1);
        soundArr.push(chanel);
    }
    else{
        sound = await RES.getResAsync(type + "_mp3")
        let chanel = sound.play(0, 1);
        soundArr.push(chanel);
    }
}

export const stopAllSound = () => {
    for(let i = 0; i < soundArr.length; i ++){
        soundArr[i].stop();
    }
};