const MamiAudioSourceDummy = function() {
    return {
        play: async () => {},
        stop: () => {},
        getRate: () => 0,
        setRate: rate => {},
        getDetune: () => 0,
        setDetune: rate => {},
        getVolume: () => 0,
        setVolume: volume => {},
        isMuted: () => true,
        setMuted: mute => {},
        setLoop: (loop, start, end) => {},
    };
};

const MamiAudioSource = function(source, gain, buffer) {
    let volume = 1,
        isMuted = false;

    let hasDisconnected = false;

    const disconnect = () => {
        if(hasDisconnected)
            return;
        hasDisconnected = true;

        gain.disconnect();
        source.disconnect();
    };

    source.addEventListener('ended', () => disconnect());

    return {
        play: () => {
            return new Promise(resolve => {
                source.addEventListener('ended', () => resolve());
                source.start();
            });
        },
        stop: () => {
            source.stop();
            disconnect();
        },

        getRate: () => source.playbackRate.value,
        setRate: rate => {
            source.playbackRate.value = Math.min(
                source.playbackRate.maxValue,
                Math.max(
                    source.playbackRate.minValue,
                    rate
                )
            );
        },
        getDetune: () => source.detune.value,
        setDetune: rate => {
            source.detune.value = Math.min(
                source.detune.maxValue,
                Math.max(
                    source.detune.minValue,
                    rate
                )
            );
        },

        getVolume: () => volume,
        setVolume: vol => {
            volume = vol;
            if(!isMuted)
                gain.gain.value = volume;
        },
        isMuted: () => isMuted,
        setMuted: mute => {
            gain.gain.value = (isMuted = mute) ? 0 : volume;
        },

        setLoop: (loop, start, end) => {
            if(typeof start === 'number')
                source.loopStart = start;
            if(typeof end === 'number')
                source.loopEnd = end;
            source.loop = !!loop;
        },
    };
};
