class AudiosMgr {
	private static _instance: AudiosMgr;

	static get instance(): AudiosMgr {
		if (!this._instance) {
			this._instance = new AudiosMgr();
		}
		return this._instance;
	}
	private audioLoaded: boolean = false;
	private audiosRes = {};
	public firstBgm: boolean = true;
	public bgmAllow: boolean = localStorage.getItem('bgmAllow') !== 'false';
	private bgm: egret.SoundChannel;
	private bgmPosition: number = 0;
	private constructor() {
	}

	public loaded(): void {
		this.audioLoaded = true;
		this.playBgm();
	}

	/**获取sound资源 */
	private getAudioSource(soundName: string): egret.Sound {
		this.audiosRes[soundName] = this.audiosRes[soundName] || RES.getRes(soundName);

		return this.audiosRes[soundName];
	}

	private playSound(soundName: string, startTime: number = 0, loops: number = 1): egret.SoundChannel {
		return this.getAudioSource(soundName).play(startTime, loops);
	}

	public setBgmAllow(allow: boolean): void {
		this.bgmAllow = allow;
		localStorage.setItem('bgmAllow', allow.toString())
	}

	public playBgm(): void {
		if (!this.audioLoaded || !this.bgmAllow) return;
		if (this.bgm) return;

		DEBUG && console.log('play bgm');

		this.bgm = this.playSound('bgm_mp3', this.bgmPosition, 0);

		//第一次主动播放失败
		this.firstBgm && setTimeout(() => {
			if (this.bgm.position == 0) {
				this.stopBgm();
			}
		}, 100);

		Index.instance.setMusicToggle(true);

		this.firstBgm = false;
	}

	public stopBgm(): void {
		if (this.bgm) {
			DEBUG && console.log('stop bgm');
			this.bgmPosition = this.bgm.position;
			this.bgm.stop();
			this.bgm = null;
			Index.instance.setMusicToggle(false);
			this.setBgmAllow(false);
		}
	}

	public playButtonClick(): egret.SoundChannel {
		if (!this.audioLoaded || !this.bgmAllow) return null;
		return this.playSound('button-click_mp3');
	}

	public playNewRound(): egret.SoundChannel {
		if (!this.audioLoaded || !this.bgmAllow) return null;
		return this.playSound('xindeyilun_mp3');
	}

	public playWin(): egret.SoundChannel {
		if (!this.audioLoaded || !this.bgmAllow) return null;
		return this.playSound('wintexiao_mp3');
	}
}