"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.scheduleWith = exports.scheduleWith_ = void 0;
const CK = __importStar(require("../../../../Collections/Immutable/Chunk"));
const T = __importStar(require("../../../../Effect"));
const SC = __importStar(require("../../../../Schedule"));
const CH = __importStar(require("../../Channel"));
const C = __importStar(require("../core"));
/**
 * Schedules the output of the stream using the provided `schedule` and emits its output at
 * the end (if `schedule` is finite).
 * Uses the provided function to align the stream and schedule outputs on the same type.
 */
function scheduleWith_(self, schedule, f, g) {
    const loop = (driver, chunk, index) => {
        if (index < CK.size(chunk)) {
            return CH.unwrap(T.suspend(() => {
                const a = CK.unsafeGet_(chunk, index);
                return T.foldM_(driver.next(a), () => T.zipLeft_(T.map_(T.orDie(driver.last), (b) => CH.zipRight_(CH.write(CK.many(f(a), g(b))), loop(driver, chunk, index + 1))), driver.reset), () => T.succeed(CH.zipRight_(CH.write(CK.single(f(a))), loop(driver, chunk, index + 1))));
            }));
        }
        else {
            return CH.readWithCause((chunk) => loop(driver, chunk, 0), (_) => CH.failCause(_), (_) => CH.end(_));
        }
    };
    return new C.Stream(CH.chain_(CH.fromEffect(SC.driver(schedule)), (_) => self.channel[">>>"](loop(_, CK.empty(), 0))));
}
exports.scheduleWith_ = scheduleWith_;
/**
 * Schedules the output of the stream using the provided `schedule` and emits its output at
 * the end (if `schedule` is finite).
 * Uses the provided function to align the stream and schedule outputs on the same type.
 *
 * @ets_data_first scheduleWith_
 */
function scheduleWith(schedule, f, g) {
    return (self) => scheduleWith_(self, schedule, f, g);
}
exports.scheduleWith = scheduleWith;
//# sourceMappingURL=scheduleWith.js.map