"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.mapAccumEffect = exports.mapAccumEffect_ = 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 CH = __importStar(require("../../Channel"));
const C = __importStar(require("../core"));
/**
 * Statefully and effectfully maps over the elements of this stream to produce
 * new elements.
 */
function mapAccumEffect_(self, s, f) {
    const accumulator = (s) => CH.readWith((in_) => CH.unwrap(T.suspend(() => {
        const outputChunk = CK.builder();
        const emit = (a) => T.asUnit(T.succeedWith(() => {
            outputChunk.append(a);
        }));
        return (T.fold_(T.reduce_(in_, s, (s1, a) => T.chain_(f(s1, a), (sa) => T.as_(emit(Tp.get_(sa, 1)), Tp.get_(sa, 0)))), (failure) => {
            const partialResult = outputChunk.build();
            if (!CK.isEmpty(partialResult)) {
                return CH.zipRight_(CH.write(partialResult), CH.fail(failure));
            }
            else {
                return CH.fail(failure);
            }
        }, (_) => CH.zipRight_(CH.write(outputChunk.build()), accumulator(_))));
    })), (_) => CH.fail(_), (_) => CH.unit);
    return new C.Stream(self.channel[">>>"](accumulator(s)));
}
exports.mapAccumEffect_ = mapAccumEffect_;
/**
 * Statefully and effectfully maps over the elements of this stream to produce
 * new elements.
 *
 * @ets_data_first mapAccumEffect_
 */
function mapAccumEffect(s, f) {
    return (self) => mapAccumEffect_(self, s, f);
}
exports.mapAccumEffect = mapAccumEffect;
//# sourceMappingURL=mapAccumEffect.js.map