"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeWith = exports.mergeWith_ = void 0;
// ets_tracing: off
const T = __importStar(require("../../../../Effect"));
const E = __importStar(require("../../../../Either"));
const Ex = __importStar(require("../../../../Exit"));
const F = __importStar(require("../../../../Fiber"));
const Function_1 = require("../../../../Function");
const M = __importStar(require("../../../../Managed"));
const MH = __importStar(require("../_internal/mergeHelpers"));
const C = __importStar(require("../core"));
const FromInput = __importStar(require("./fromInput"));
const ToPull = __importStar(require("./toPull"));
const Unwrap = __importStar(require("./unwrap"));
const UnwrapManaged = __importStar(require("./unwrapManaged"));
const ZipRight = __importStar(require("./zipRight"));
/**
 * Returns a new channel, which is the merge of this channel and the specified channel, where
 * the behavior of the returned channel on left or right early termination is decided by the
 * specified `leftDone` and `rightDone` merge decisions.
 */
function mergeWith_(self, that, leftDone, rightDone) {
    const m = (M.map_(M.bind_(M.bind_(M.let_(M.bind_(M.do, "input", () => T.toManaged(C.makeSingleProducerAsyncInput())), "queueReader", ({ input }) => FromInput.fromInput(input)), "pullL", ({ queueReader }) => ToPull.toPull(queueReader[">>>"](self))), "pullR", ({ queueReader }) => ToPull.toPull(queueReader[">>>"](that))), ({ input, pullL, pullR }) => {
        const handleSide = (exit, fiber, pull) => (done, both, single) => {
            const onDecision = (decision) => {
                MH.concrete(decision);
                if (decision._typeId === MH.DoneTypeId) {
                    return T.succeed(C.fromEffect(T.zipRight_(F.interrupt(fiber), decision.io)));
                }
                else {
                    return T.map_(fiber.await, Ex.fold((cause) => C.fromEffect(decision.f(Ex.halt(cause))), E.fold((z) => C.fromEffect(decision.f(Ex.succeed(z))), (elem) => ZipRight.zipRight_(C.write(elem), go(single(decision.f))))));
                }
            };
            return Ex.fold_(exit, (failure) => onDecision(done(Ex.halt(failure))), E.fold((z) => onDecision(done(Ex.succeed(z))), (elem) => T.map_(T.forkDaemon(pull), (leftFiber) => ZipRight.zipRight_(C.write(elem), go(both(leftFiber, fiber))))));
        };
        const go = (state) => {
            if (state._typeId === MH.BothRunningTypeId) {
                const lj = F.join(state.left);
                const rj = F.join(state.right);
                return Unwrap.unwrap(T.raceWith_(lj, rj, (leftEx, _) => handleSide(leftEx, state.right, pullL)(leftDone, (l, r) => new MH.BothRunning(l, r), (_) => new MH.LeftDone(_)), (rightEx, _) => handleSide(rightEx, state.left, pullR)(rightDone, (l, r) => new MH.BothRunning(r, l), (_) => new MH.RightDone(_))));
            }
            else if (state._typeId === MH.LeftDoneTypeId) {
                return Unwrap.unwrap(T.map_(T.result(pullR), Ex.fold((cause) => C.fromEffect(state.f(Ex.halt(cause))), E.fold((z) => C.fromEffect(state.f(Ex.succeed(z))), (elem) => ZipRight.zipRight_(C.write(elem), go(new MH.LeftDone(state.f)))))));
            }
            else {
                return Unwrap.unwrap(T.map_(T.result(pullL), Ex.fold((cause) => C.fromEffect(state.f(Ex.halt(cause))), E.fold((z) => C.fromEffect(state.f(Ex.succeed(z))), (elem) => ZipRight.zipRight_(C.write(elem), go(new MH.RightDone(state.f)))))));
            }
        };
        return (C.embedInput_(C.chain_(C.fromEffect(T.zipWith_(T.forkDaemon(pullL), T.forkDaemon(pullR), (a, b) => new MH.BothRunning(a, b))), go), input));
    }));
    return UnwrapManaged.unwrapManaged(m);
}
exports.mergeWith_ = mergeWith_;
/**
 * Returns a new channel, which is the merge of this channel and the specified channel, where
 * the behavior of the returned channel on left or right early termination is decided by the
 * specified `leftDone` and `rightDone` merge decisions.
 *
 * @ets_data_first mergeWith_
 */
function mergeWith(that, leftDone, rightDone) {
    return (self) => mergeWith_(self, that, leftDone, rightDone);
}
exports.mergeWith = mergeWith;
//# sourceMappingURL=mergeWith.js.map