"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Holder_1 = require("../../../../../Class/Holder");
const Waiter_1 = require("../../../../../Waiter");
const Blob_1 = require("../../../../../wrap/Blob");
const _ids_1 = require("../../../../_ids");
class _MediaRecorder extends Holder_1.Holder {
    constructor(system) {
        super({
            fi: ['opt', 'stream'],
            fo: ['blob'],
            i: ['start', 'stop'],
            o: ['err'],
        }, {
            input: {
                stream: {
                    ref: true,
                },
            },
            output: {
                blob: {
                    ref: true,
                },
            },
        }, system, _ids_1.ID_MEDIA_RECORDER);
        this._stop_waiter = new Waiter_1.Waiter();
        this._listen = () => {
            const { opt } = this._i;
            const chunks = [];
            this._media_recorder.ondataavailable = (event) => {
                const { data } = event;
                if (data.size > 0) {
                    chunks.push(data);
                }
            };
            this._media_recorder.onstop = () => {
                const blob_ = new Blob(chunks, { type: opt.mimeType ?? 'audio/wav' });
                const blob = (0, Blob_1.wrapBlob)(blob_, this.__system);
                this._done({ blob });
                this._stop_waiter.set(true);
                this._stop_waiter.clear();
            };
            this._media_recorder.onerror = (event) => {
                this._output.err.push(`error recording stream: ${event?.error?.name}`);
            };
        };
        this._unlisten = () => {
            this._media_recorder.onerror = undefined;
            this._media_recorder.ondataavailable = undefined;
            this._media_recorder.onstop = undefined;
        };
        this._start_recorder = () => {
            if (this._media_recorder) {
                this._listen();
                try {
                    this._media_recorder.start();
                }
                catch (err) {
                    if (err.message.toLowerCase().startsWith('failed to execute')) {
                        this.err('failed to start media recorder');
                    }
                    else {
                        this.err(err.message.toLowerCase());
                    }
                }
            }
        };
    }
    async f({ opt, stream }, done, fail) {
        const _stream = await stream.mediaStream();
        try {
            this._media_recorder = new MediaRecorder(_stream, opt);
        }
        catch (err) {
            fail(err.message.toLowerCase());
            return;
        }
        const start = this._input.start.peak();
        if (start !== undefined) {
            this._start_recorder();
        }
    }
    d() {
        if (this._media_recorder) {
            this._unlisten();
            this._media_recorder.stop();
            this._media_recorder = undefined;
        }
    }
    async onIterDataInputData(name, data) {
        super.onIterDataInputData(name, data);
        if (name === 'start') {
            this._start_recorder();
        }
        else if (name === 'stop') {
            if (this._media_recorder) {
                if (this._media_recorder.state === 'recording') {
                    this._media_recorder.stop();
                }
                await this._stop_waiter.once();
                this._backward('start');
                this._backward('stop');
            }
        }
    }
    onIterDataInputDrop(name) {
        if (this.hasErr()) {
            this.takeErr();
        }
        if (name === 'start') {
            if (!this._backwarding) {
                if (this._media_recorder) {
                    this._unlisten();
                    this._media_recorder.stop();
                }
            }
        }
    }
}
exports.default = _MediaRecorder;
//# sourceMappingURL=index.js.map