"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
const Parser = require("stream-parser");
const inherits = require("util").inherits;
const Transform = require("stream").Transform;
function Throttle(opts) {
    if (!(this instanceof Throttle)) return new Throttle(opts);
    if ("number" == typeof opts) opts = {
        bps: opts
    };
    if (!opts) opts = {};
    if (null == opts.lowWaterMark) opts.lowWaterMark = 0;
    if (null == opts.highWaterMark) opts.highWaterMark = 0;
    if (null == opts.bps) throw new Error('must pass a "bps" bytes-per-second option');
    if (null == opts.chunkSize) opts.chunkSize = opts.bps / 10 | 0;
    Transform.call(this, opts);
    this.bps = opts.bps;
    this.chunkSize = Math.max(1, opts.chunkSize);
    this.totalBytes = 0;
    this.startTime = Date.now();
    this._passthroughChunk();
}
inherits(Throttle, Transform);
Parser(Throttle.prototype);
Throttle.prototype._passthroughChunk = function() {
    this._passthrough(this.chunkSize, this._onchunk);
    this.totalBytes += this.chunkSize;
};
Throttle.prototype._onchunk = function(output, done) {
    const self = this;
    const totalSeconds = (Date.now() - this.startTime) / 1000;
    const expected = totalSeconds * this.bps;
    function d() {
        self._passthroughChunk();
        done();
    }
    if (this.totalBytes > expected) {
        const remainder = this.totalBytes - expected;
        const sleepTime = remainder / this.bps * 1000;
        if (sleepTime > 0) {
            setTimeout(d, sleepTime);
        } else {
            d();
        }
    } else {
        d();
    }
};

//# sourceMappingURL=upload-test.js.map