import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';

var Scheduler = /*#__PURE__*/function () {
  /**
   * 异步任务调度器，同一时间只能执行 n 个任务
   * @param {number} [maxConcurrency] 最多同时执行的任务数目，默认为 2
   *
   * @example
   * ```ts
   * let scheduler;
   *
   * export async function login({
   *   userId,
   *   userSig,
   *   tim,
   * }: {
   *   userId: string;
   *   userSig: string;
   *   tim: IChatSDK;
   * }) {
   *   if (!scheduler) {
   *     scheduler = new Scheduler(1);
   *   }
   *
   *   return await scheduler.add(innerLogin.bind(null, {
   *     userId,
   *     userSig,
   *     tim,
   *   }));
   * }
   * ```
   */
  function Scheduler() {
    var _this = this;
    var maxConcurrency = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 2;
    _classCallCheck(this, Scheduler);
    this.doJob = function () {
      if (_this.doingJobs < _this.maxConcurrency && _this.pendingState.length) {
        _this.doingJobs += 1;
        var job = _this.pendingState.shift();
        if (!job) {
          return;
        }
        job().then(function (res) {
          var _a;
          _this.doingJobs -= 1;
          (_a = job.resolve) === null || _a === void 0 ? void 0 : _a.call(job, res);
          _this.doJob();
        })["catch"](function (e) {
          var _a;
          _this.doingJobs -= 1;
          (_a = job.reject) === null || _a === void 0 ? void 0 : _a.call(job, e);
          _this.doJob();
        })["finally"](function () {});
      }
    };
    this.pendingState = [];
    this.doingJobs = 0;
    this.maxConcurrency = maxConcurrency;
  }
  return _createClass(Scheduler, [{
    key: "add",
    value: function add(promiseCreator) {
      var _this2 = this;
      return new Promise(function (resolve, reject) {
        // 关键是给传过来的函数加个回调属性，当resolved的时候，就能返回对应的结果了。
        promiseCreator.resolve = resolve;
        promiseCreator.reject = reject;
        _this2.pendingState.push(promiseCreator);
        _this2.doJob();
      });
    }
  }, {
    key: "unshift",
    value: function unshift(promiseCreator) {
      var _this3 = this;
      return new Promise(function (resolve, reject) {
        // 关键是给传过来的函数加个回调属性，当resolved的时候，就能返回对应的结果了。
        promiseCreator.resolve = resolve;
        promiseCreator.reject = reject;
        _this3.pendingState.unshift(promiseCreator);
        _this3.doJob();
      });
    }
  }]);
}();

export { Scheduler };
