"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _util = require("@polkadot/util");

// Copyright 2017-2019 @polkadot/api authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
class Combinator {
  constructor(fns, callback) {
    this._allHasFired = false;
    this._callback = void 0;
    this._fired = [];
    this._fns = [];
    this._isActive = true;
    this._results = [];
    this._subscriptions = [];
    this._callback = callback; // eslint-disable-next-line @typescript-eslint/require-await

    this._subscriptions = fns.map(async (input, index) => {
      const [fn, ...args] = Array.isArray(input) ? input : [input];

      this._fired.push(false);

      this._fns.push(fn); // Not quite 100% how to have a variable number at the front here


      return fn(...args, this.createCallback(index));
    });
  }

  allHasFired() {
    if (!this._allHasFired) {
      this._allHasFired = this._fired.filter(hasFired => !hasFired).length === 0;
    }

    return this._allHasFired;
  }

  createCallback(index) {
    return value => {
      this._fired[index] = true;
      this._results[index] = value;
      this.triggerUpdate();
    };
  }

  triggerUpdate() {
    if (!this._isActive || !(0, _util.isFunction)(this._callback) || !this.allHasFired()) {
      return;
    }

    try {
      this._callback(this._results);
    } catch (error) {// swallow, we don't want the handler to trip us up
    }
  }

  unsubscribe() {
    if (!this._isActive) {
      return;
    }

    this._isActive = false; // eslint-disable-next-line @typescript-eslint/no-misused-promises

    this._subscriptions.forEach(async subscription => {
      try {
        const unsubscribe = await subscription;

        if ((0, _util.isFunction)(unsubscribe)) {
          unsubscribe();
        }
      } catch (error) {// ignore
      }
    });
  }

}

exports.default = Combinator;