"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.foldSink = exports.foldSink_ = void 0;
// ets_tracing: off
const CK = __importStar(require("../../../Collections/Immutable/Chunk"));
const AR = __importStar(require("../../../Support/AtomicReference"));
const CH = __importStar(require("../Channel"));
const C = __importStar(require("./core"));
function foldSink_(self, failure, success) {
    return new C.Sink(CH.foldChannel_(CH.doneCollect(self.channel), (_) => failure(_).channel, ({ tuple: [leftovers, z] }) => CH.suspend(() => {
        const leftoversRef = new AR.AtomicReference(CK.filter_(leftovers, (a) => !CK.isEmpty(a)));
        const refReader = CH.chain_(CH.succeedWith(() => leftoversRef.getAndSet(CK.empty())), (chunk) => CH.writeChunk(chunk));
        const passthrough = CH.identity();
        const continationSink = CH.zipRight_(refReader, passthrough)[">>>"](success(z).channel);
        return CH.chain_(CH.doneCollect(continationSink), ({ tuple: [newLeftovers, z1] }) => CH.zipRight_(CH.chain_(CH.succeedWith(() => leftoversRef.get), (_) => CH.writeChunk(_)), CH.as_(CH.writeChunk(newLeftovers), z1)));
    })));
}
exports.foldSink_ = foldSink_;
/**
 *
 * @ets_data_first foldSink_
 */
function foldSink(failure, success) {
    return (self) => foldSink_(self, failure, success);
}
exports.foldSink = foldSink;
//# sourceMappingURL=foldSink.js.map