"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.windowWhen = void 0;
const Observable_js_1 = require("../Observable.js");
const Subject_js_1 = require("../Subject.js");
const noop_js_1 = require("../util/noop.js");
function windowWhen(closingSelector) {
    return (source) => new Observable_js_1.Observable((destination) => {
        let window;
        let closingSubscriber;
        const handleError = (err) => {
            window.error(err);
            destination.error(err);
        };
        const openWindow = () => {
            closingSubscriber?.unsubscribe();
            window?.complete();
            window = new Subject_js_1.Subject();
            destination.next(window.asObservable());
            let closingNotifier;
            try {
                closingNotifier = (0, Observable_js_1.from)(closingSelector());
            }
            catch (err) {
                handleError(err);
                return;
            }
            closingNotifier.subscribe((closingSubscriber = (0, Observable_js_1.operate)({
                destination,
                next: openWindow,
                error: handleError,
                complete: noop_js_1.noop,
            })));
        };
        openWindow();
        source.subscribe((0, Observable_js_1.operate)({
            destination,
            next: (value) => window.next(value),
            error: handleError,
            complete: () => {
                window.complete();
                destination.complete();
            },
            finalize: () => {
                closingSubscriber?.unsubscribe();
                window = null;
            },
        }));
    });
}
exports.windowWhen = windowWhen;