"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.windowToggle = void 0;
const Observable_js_1 = require("../Observable.js");
const Subject_js_1 = require("../Subject.js");
const noop_js_1 = require("../util/noop.js");
const arrRemove_js_1 = require("../util/arrRemove.js");
function windowToggle(openings, closingSelector) {
    return (source) => new Observable_js_1.Observable((destination) => {
        const windows = [];
        const handleError = (err) => {
            while (0 < windows.length) {
                windows.shift().error(err);
            }
            destination.error(err);
        };
        (0, Observable_js_1.from)(openings).subscribe((0, Observable_js_1.operate)({
            destination,
            next: (openValue) => {
                const window = new Subject_js_1.Subject();
                windows.push(window);
                const closingSubscription = new Observable_js_1.Subscription();
                const closeWindow = () => {
                    (0, arrRemove_js_1.arrRemove)(windows, window);
                    window.complete();
                    closingSubscription.unsubscribe();
                };
                let closingNotifier;
                try {
                    closingNotifier = (0, Observable_js_1.from)(closingSelector(openValue));
                }
                catch (err) {
                    handleError(err);
                    return;
                }
                destination.next(window);
                closingSubscription.add(closingNotifier.subscribe((0, Observable_js_1.operate)({
                    destination,
                    next: closeWindow,
                    error: handleError,
                    complete: noop_js_1.noop,
                })));
            },
            complete: noop_js_1.noop,
        }));
        source.subscribe((0, Observable_js_1.operate)({
            destination,
            next: (value) => {
                const windowsCopy = windows.slice();
                for (const window of windowsCopy) {
                    window.next(value);
                }
            },
            error: handleError,
            complete: () => {
                while (0 < windows.length) {
                    windows.shift().complete();
                }
                destination.complete();
            },
            finalize: () => {
                while (0 < windows.length) {
                    windows.shift().unsubscribe();
                }
            },
        }));
    });
}
exports.windowToggle = windowToggle;//# sourceMappingURL=http://go/sourcemap/sourcemaps/bf249e6efb5b097f23d7e21d7283429f0760b740/node_modules/rxjs/dist/cjs/internal/operators/windowToggle.js.map