"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Primitive_1 = require("./Primitive");
const array_1 = require("./util/array");
const ID_SEARIAL = '_136a38b6-155a-4ed2-85cd-90bc94688f42';
class Serial extends Primitive_1.Primitive {
    constructor(system) {
        super({
            i: ['a'],
            o: [],
        }, {}, system, ID_SEARIAL);
        this._current = undefined;
        this._index = undefined;
        this._o_name = ['a'];
        this.addListener('set_output', (name, output) => {
            if (this._current !== undefined) {
                this._forwarding = true;
                if (this._o_count === 1) {
                    output.push(this._current);
                }
                this._forwarding = false;
            }
            this._o_name = Array.from(this._o_name_set).sort();
        });
        this.addListener('reset', () => {
            this._current = undefined;
            this._index = undefined;
        });
    }
    _forward_all_empty(from = 0) {
        this._forwarding_empty = true;
        (0, array_1.forEach)(this._o_name, (name, index) => {
            if (index >= from) {
                this._output[name].pull();
            }
        });
        this._forwarding_empty = false;
    }
    _current_name() {
        const current_name = this._o_name[this._index];
        return current_name;
    }
    _output_current() {
        const current_name = this._current_name();
        const pin = this._output[current_name];
        pin.push(this._current);
    }
    onDataInputData(name, data) {
        if (this._index !== undefined) {
            this._forward_all_empty(1);
        }
        this._index = 0;
        this._current = data;
        if (this._o_count > 0) {
            this._output_current();
        }
    }
    onDataInputDrop(name) {
        this._index = undefined;
        this._forward_all_empty();
    }
    onDataOutputDrop(name) {
        if (!this._forwarding_empty) {
            if (this._index < this._o_count - 1) {
                this._index++;
                this._output_current();
            }
            else {
                this._index = undefined;
                this._current = undefined;
                this._input.a.pull();
            }
        }
    }
}
exports.default = Serial;
//# sourceMappingURL=Serial.js.map