"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpeechRecorder = void 0;
const EventEmitter_1 = require("../../EventEmitter");
const callAll_1 = require("../../util/call/callAll");
class SpeechRecorder extends EventEmitter_1.EventEmitter_ {
    constructor(__system, opt) {
        super();
        this._recording = false;
        const { api: { speech: { SpeechGrammarList, SpeechRecognition }, }, } = __system;
        if (SpeechRecognition) {
            const { grammars, lang = 'en-US', continuous = false, interimResults = false, maxAlternatives = 1, } = opt;
            let recognition;
            try {
                recognition = new SpeechRecognition({
                    grammars,
                    lang,
                    interimResults,
                    maxAlternatives,
                    continuous,
                });
            }
            catch (err) {
                throw err;
            }
            this._unlisten = (0, callAll_1.callAll)([
                recognition.addEventListener('error', ({ error }) => {
                    if (error === 'no-speech') {
                        return;
                    }
                }),
                recognition.addEventListener('end', () => {
                    if (this._recording) {
                        recognition.start();
                    }
                    else {
                        this.emit('end');
                    }
                }),
                recognition.addEventListener('result', (event) => {
                    const { results } = event;
                    const firstResult = results[0];
                    const firstAlternative = firstResult[0];
                    const { transcript, confidence } = firstAlternative;
                    this.emit('transcript', transcript);
                }),
            ]);
            this._recognition = recognition;
        }
    }
    start() {
        if (this._recognition) {
            if (!this._recording) {
                this._recording = true;
                this._recognition.start();
            }
        }
    }
    stop() {
        if (this._recognition) {
            if (this._recording) {
                this._recording = false;
                // stop provides faster recognition (than abort), but it can
                // throw an exception if it is called twice in a row - swallow it
                try {
                    this._recognition.stop();
                }
                catch {
                    // Expected: stop() throws if called twice per Web Speech API spec
                }
                // this._recognition.abort()
            }
        }
    }
}
exports.SpeechRecorder = SpeechRecorder;
//# sourceMappingURL=index.js.map