"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.repeatElementsWith = void 0;
const A = __importStar(require("../../Collections/Immutable/Chunk"));
const Function_1 = require("../../Function");
const O = __importStar(require("../../Option"));
const SC = __importStar(require("../../Schedule"));
const T = __importStar(require("../_internal/effect"));
const M = __importStar(require("../_internal/managed"));
const Ref = __importStar(require("../_internal/ref"));
const BP = __importStar(require("../BufferedPull"));
const definitions_1 = require("./definitions");
/**
 * Repeats each element of the stream using the provided schedule. When the schedule is finished,
 * then the output of the schedule will be emitted into the stream. Repetitions are done in
 * addition to the first execution, which means using `Schedule.recurs(1)` actually results in
 * the original effect, plus an additional recurrence, for a total of two repetitions of each
 * value in the stream.
 *
 * This function accepts two conversion functions, which allow the output of this stream and the
 * output of the provided schedule to be unified into a single type. For example, `Either` or
 * similar data type.
 */
function repeatElementsWith(schedule) {
    return (f, g) => (self) => new definitions_1.Stream((M.map_(M.let_(M.bind_(M.bind_(M.bind_(M.do, "as", () => M.mapM_(self.proc, (_) => BP.make(_))), "driver", () => T.toManaged(SC.driver(schedule))), "state", () => T.toManaged(Ref.makeRef(O.none))), "pull", ({ as, driver, state }) => {
        const go = T.chain_(state.get, O.fold(() => T.chain_(BP.pullElement(as), (o) => T.as_(state.set(O.some(o)), A.single(f(o)))), (o) => {
            const advance = T.as_(driver.next(o), A.single(f(o)));
            const reset = (T.zipLeft_(T.zipLeft_(T.map_(T.orDie(driver.last), (b) => A.single(g(b))), driver.reset), state.set(O.none)));
            return T.orElse_(advance, () => reset);
        }));
        return go;
    }), ({ pull }) => pull)));
}
exports.repeatElementsWith = repeatElementsWith;
//# sourceMappingURL=repeatElementsWith.js.map