"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeInternals = void 0;
const Observable_js_1 = require("../Observable.js");
const executeSchedule_js_1 = require("../util/executeSchedule.js");
function mergeInternals(source, destination, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
    const buffer = [];
    let active = 0;
    let index = 0;
    let isComplete = false;
    const checkComplete = () => {
        if (isComplete && !buffer.length && !active) {
            destination.complete();
        }
    };
    const outerNext = (value) => (active < concurrent ? doInnerSub(value) : buffer.push(value));
    const doInnerSub = (value) => {
        expand && destination.next(value);
        active++;
        let innerComplete = false;
        (0, Observable_js_1.from)(project(value, index++)).subscribe((0, Observable_js_1.operate)({
            destination,
            next: (innerValue) => {
                onBeforeNext?.(innerValue);
                if (expand) {
                    outerNext(innerValue);
                }
                else {
                    destination.next(innerValue);
                }
            },
            complete: () => {
                innerComplete = true;
            },
            finalize: () => {
                if (innerComplete) {
                    try {
                        active--;
                        while (buffer.length && active < concurrent) {
                            const bufferedValue = buffer.shift();
                            if (innerSubScheduler) {
                                (0, executeSchedule_js_1.executeSchedule)(destination, innerSubScheduler, () => doInnerSub(bufferedValue));
                            }
                            else {
                                doInnerSub(bufferedValue);
                            }
                        }
                        checkComplete();
                    }
                    catch (err) {
                        destination.error(err);
                    }
                }
            },
        }));
    };
    source.subscribe((0, Observable_js_1.operate)({
        destination,
        next: outerNext,
        complete: () => {
            isComplete = true;
            checkComplete();
        },
    }));
    return () => {
        additionalFinalizer?.();
    };
}
exports.mergeInternals = mergeInternals;//# sourceMappingURL=http://go/sourcemap/sourcemaps/63a2996a10d9e476b6c28e951dd7691d9c0cf480/node_modules/rxjs/dist/cjs/internal/operators/mergeInternals.js.map