"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bufferToggle = void 0;
const Observable_js_1 = require("../Observable.js");
const noop_js_1 = require("../util/noop.js");
const arrRemove_js_1 = require("../util/arrRemove.js");
function bufferToggle(openings, closingSelector) {
    return (source) => new Observable_js_1.Observable((destination) => {
        const buffers = [];
        (0, Observable_js_1.from)(openings).subscribe((0, Observable_js_1.operate)({
            destination,
            next: (openValue) => {
                const buffer = [];
                buffers.push(buffer);
                const closingSubscription = new Observable_js_1.Subscription();
                const emitBuffer = () => {
                    (0, arrRemove_js_1.arrRemove)(buffers, buffer);
                    destination.next(buffer);
                    closingSubscription.unsubscribe();
                };
                closingSubscription.add((0, Observable_js_1.from)(closingSelector(openValue)).subscribe((0, Observable_js_1.operate)({ destination, next: emitBuffer, complete: noop_js_1.noop })));
            },
            complete: noop_js_1.noop,
        }));
        source.subscribe((0, Observable_js_1.operate)({
            destination,
            next: (value) => {
                for (const buffer of buffers) {
                    buffer.push(value);
                }
            },
            complete: () => {
                while (buffers.length > 0) {
                    destination.next(buffers.shift());
                }
                destination.complete();
            },
        }));
    });
}
exports.bufferToggle = bufferToggle;