"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) {
        const { api: { speech: { SpeechSynthesis, SpeechSynthesisUtterance }, }, } = this.__system;
        if (message === '') {
            done();
            return;
        }
        let synth;
        try {
            synth = SpeechSynthesis({});
        }
        catch (err) {
            done(undefined, err.message);
            return;
        }
        let voices = [];
        const speak = () => {
            voices = synth.getVoices();
            if (voices.length > 0) {
                _speak();
            }
            else {
                // AD HOC
                // [Chrome]
                setTimeout(() => {
                    speak();
                }, 100);
            }
        };
        const _speak = () => {
            if (voice < 0 || voice > voices.length - 1) {
                done(undefined, 'voice index out of range');
                return;
            }
            const _voice = voices[voice];
            const utterance = SpeechSynthesisUtterance({
                text: message,
                voice: _voice,
            });
            utterance.addEventListener('error', (err) => {
                done(undefined, err.error);
            });
            utterance.addEventListener('end', () => {
                done();
            });
            synth.speak(utterance);
        };
        speak();
    }
}
exports.default = TextToSpeech;
//# sourceMappingURL=index.js.map