import Resonator from '../framework/resonator';


export default class Sound {
    constructor() {
        this.res = new Resonator();
        this.ambience = null;
        this.music = null;
        this.ambienceVolume = 1;
        this.musicVolume = 1;
        this.sfxVolume = 1;
        this.previousAmbience = "";
        this.previousMusic = "";
    }

    play(file) {
        const sound = this.res.loadImmediate(file);
        sound.setVolume(this.sfxVolume);
        sound.play();
    }

    async setAmbience(file) {
        if (file === this.previousAmbience) return;
        if (this.ambience) {
            const previousAmbience = this.ambience;
            this.ambience = null;
            setTimeout(() => previousAmbience.fadeOut(6), 1500);
            setTimeout(() => previousAmbience.destroy(), 6000);
        }
        if (!file) return;
        this.previousAmbience = file;
        this.ambience = this.res.stream(file, 0);
        this.ambience.setVolume(this.ambienceVolume);
        this.ambience.play();
        this.ambience.loop(true);
        this.ambience.fadeIn(3);
    }

    setMusic(file) {
        if (file === this.previousMusic) return;
        if (this.music) {
            const previousMusic = this.music;
            setTimeout(() => previousMusic.fadeOut(2), 500);
            setTimeout(() => previousMusic.destroy(), 2000);
        }
        if (!file) return;
        this.previousMusic = file;
        this.music = this.res.stream(file, 1);
        this.music.setVolume(this.musicVolume);
        this.music.play();
        this.music.fadeIn(2);
    }

    setImpulse(file) {
        this.res.setEnvironmentImpulse(file);
    }

    setMusicVolume(volume) {
        this.musicVolume = volume;
        if (this.music) this.music.setVolume(volume);
    }

    setAmbienceVolume(volume) {
        this.ambienceVolume = volume;
        if (this.ambience) this.ambience.setVolume(volume);
    }

    setSFXVolume(volume) {
        this.sfxVolume = volume;
    }
}