"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.throttleShapeEffect = exports.throttleShapeEffect_ = void 0;
// ets_tracing: off
const CL = __importStar(require("../../../../Clock"));
const T = __importStar(require("../../../../Effect"));
const Function_1 = require("../../../../Function");
const CH = __importStar(require("../../Channel"));
const C = __importStar(require("../core"));
/**
 * Delays the chunks of this stream according to the given bandwidth parameters using the token bucket
 * algorithm. Allows for burst in the processing of elements by allowing the token bucket to accumulate
 * tokens up to a `units + burst` threshold. The weight of each chunk is determined by the `costFn`
 * effectful function.
 */
function throttleShapeEffect_(self, units, duration, costFn, burst = 0) {
    const loop = (tokens, timestamp) => CH.readWith((in_) => CH.unwrap((T.map_(T.bind_(T.bind_(T.do, "weight", () => costFn(in_)), "current", () => CL.currentTime), ({ current, weight }) => {
        const elapsed = current - timestamp;
        const cycles = elapsed - duration;
        const available = (() => {
            const sum = Math.floor(tokens + cycles * units);
            const max = units + burst < 0 ? Number.MAX_SAFE_INTEGER : units + burst;
            return sum < 0 ? max : Math.min(sum, max);
        })();
        const remaining = available - weight;
        const waitCycles = remaining >= 0 ? 0 : -remaining / units;
        const delay = Math.floor(waitCycles * duration);
        if (delay > 0) {
            return CH.zipRight_(CH.zipRight_(CH.fromEffect(CL.sleep(delay)), CH.write(in_)), loop(remaining, current));
        }
        else {
            return CH.zipRight_(CH.write(in_), loop(remaining, current));
        }
    }))), (e) => CH.fail(e), (_) => CH.unit);
    return new C.Stream(CH.chain_(CH.fromEffect(CL.currentTime), (_) => self.channel[">>>"](loop(units, _))));
}
exports.throttleShapeEffect_ = throttleShapeEffect_;
/**
 * Delays the chunks of this stream according to the given bandwidth parameters using the token bucket
 * algorithm. Allows for burst in the processing of elements by allowing the token bucket to accumulate
 * tokens up to a `units + burst` threshold. The weight of each chunk is determined by the `costFn`
 * effectful function.
 *
 * @ets_data_first throttleShapeEffect_
 */
function throttleShapeEffect(units, duration, costFn, burst = 0) {
    return (self) => throttleShapeEffect_(self, units, duration, costFn, burst);
}
exports.throttleShapeEffect = throttleShapeEffect;
//# sourceMappingURL=throttleShapeEffect.js.map