"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.reduceEffect = void 0;
// ets_tracing: off
const CK = __importStar(require("../../../Collections/Immutable/Chunk"));
const Tp = __importStar(require("../../../Collections/Immutable/Tuple"));
const T = __importStar(require("../../../Effect"));
const Function_1 = require("../../../Function");
const O = __importStar(require("../../../Option"));
const CH = __importStar(require("../Channel"));
const C = __importStar(require("./core"));
/**
 * A sink that effectfully folds its inputs with the provided function, termination predicate and initial state.
 */
function reduceEffect(z, cont, f) {
    const reduceChunkSplit = (z, chunk) => (cont) => (f) => {
        const reduce = (s, chunk, idx, len) => {
            if (idx === len) {
                return T.succeed(Tp.tuple(s, O.none));
            }
            else {
                return T.chain_(f(s, CK.unsafeGet_(chunk, idx)), (s1) => {
                    if (cont(s1)) {
                        return reduce(s1, chunk, idx + 1, len);
                    }
                    else {
                        return T.succeed(Tp.tuple(s1, O.some(CK.drop_(chunk, idx + 1))));
                    }
                });
            }
        };
        return reduce(z, chunk, 0, CK.size(chunk));
    };
    const reader = (s) => {
        if (!cont(s)) {
            return CH.end(s);
        }
        else {
            return CH.readWith((_in) => {
                return (CH.chain_(CH.fromEffect(reduceChunkSplit(s, _in)(cont)(f)), ({ tuple: [nextS, leftovers] }) => {
                    return O.fold_(leftovers, () => reader(nextS), (l) => CH.as_(CH.write(l), nextS));
                }));
            }, (err) => CH.fail(err), (_) => CH.end(s));
        }
    };
    return new C.Sink(reader(z));
}
exports.reduceEffect = reduceEffect;
//# sourceMappingURL=reduceEffect.js.map