import { MutableQueue } from "./queue/MutableQueue";
import { Base64ToArrayBufferConverter } from "./Base64ToArrayBufferConverter";
/**
 * Plays an audio representation of a given message by converting the base64 payload (wav) to an ArrayBuffer
 * and then feeding this ArrayBuffer into the Web Audio API.
 *
 * To keep it simple this implementation makes the rather naive assumption that all messages that should be played
 * will be added to the queue before playing the first (initial) message is done.
 * This assumption is made to avoid complex Promise heavy code and/or a while loop that may completely block
 * the front-end.
 */
var BufferedAudioPlayer = /** @class */ (function () {
    function BufferedAudioPlayer() {
        this.queue = new MutableQueue();
        this.audioContext = new AudioContext();
        this.state = State.READY;
    }
    /**
     * Singleton to prevent the existence of multiple audio players and therefore overlapping.
     * @returns {AudioPlayer}
     */
    BufferedAudioPlayer.instance = function () {
        return this.INSTANCE || (this.INSTANCE = new this());
    };
    /**
     * Adds a message to the Queue and starts playing queued messages.
     * @param {Map<string, string>} message
     */
    BufferedAudioPlayer.prototype.play = function (message) {
        this.queue.enqueue(message);
        this.playAudio();
    };
    BufferedAudioPlayer.prototype.playAudio = function () {
        var _this = this;
        if (this.state === State.READY) {
            this.state = State.PLAYING;
            var source_1 = this.audioContext.createBufferSource();
            this.audioContext.decodeAudioData(Base64ToArrayBufferConverter.base64ToArrayBuffer(this.queue.dequeue()["base64audio"]))
                .then(function (data) {
                source_1.buffer = data;
                source_1.connect(_this.audioContext.destination);
                source_1.onended = function () {
                    _this.state = State.READY;
                    if (!_this.queue.isEmpty()) {
                        _this.playAudio();
                    }
                };
                source_1.start(0);
            });
        }
    };
    return BufferedAudioPlayer;
}());
export { BufferedAudioPlayer };
var State;
(function (State) {
    State[State["PLAYING"] = 0] = "PLAYING";
    State[State["READY"] = 1] = "READY";
})(State || (State = {}));
//# sourceMappingURL=BufferedAudioPlayer.js.map