"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Functional_1 = require("../../../../../Class/Functional");
const _ids_1 = require("../../../../_ids");
class TextToSpeech extends Functional_1.Functional {
    constructor(system) {
        super({
            i: ['message', 'voice'],
            o: [],
        }, {}, system, _ids_1.ID_TEXT_TO_SPEECH);
    }
    f({ message, voice }, done, fail) {
        const { api: { speech: { SpeechSynthesis, SpeechSynthesisUtterance }, }, } = this.__system;
        if (message === '') {
            done();
            return;
        }
        let synth;
        try {
            synth = SpeechSynthesis;
        }
        catch (err) {
            fail(err.message);
            return;
        }
        let voices = [];
        const speak = () => {
            voices = synth.getVoices();
            if (voices.length > 0) {
                _speak();
            }
            else {
                speak();
            }
        };
        const _speak = () => {
            if (voice < 0 || voice > voices.length - 1) {
                fail('voice index out of range');
                return;
            }
            const _voice = voices[voice];
            const utterance = new SpeechSynthesisUtterance(message);
            utterance.addEventListener('error', (err) => {
                fail(err.error);
            });
            utterance.addEventListener('end', () => {
                done();
            });
            synth.speak(utterance);
        };
        speak();
    }
}
exports.default = TextToSpeech;
//# sourceMappingURL=index.js.map