"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.FetchTotalState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _CollectionState = require("./CollectionState");
var _util = require("../util");
class FetchTotalState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "_collection", void 0);
    (0, _defineProperty2.default)(this, "_totalsCollection", void 0);
    this._collection = params.collection;
    const {
      errorMonitor,
      errorHandler,
      onlineState,
      history,
      translate,
      queryCache,
      lodash,
      queryName,
      itemKey,
      itemName,
      paginationMode,
      selectionConsistencyMode,
      filters,
      query: {
        search
      }
    } = params.collection;
    this._totalsCollection = new _CollectionState.CollectionState({
      errorMonitor,
      errorHandler,
      onlineState,
      history,
      hooks: params.collection.hooks,
      translate,
      queryCache,
      lodash,
      queryName: `${queryName}.total`,
      itemKey,
      itemName,
      limit: 1,
      fetchData: async query => {
        const total = await params.fetchTotal(query);
        return {
          items: [],
          total
        };
      },
      paginationMode: paginationMode.id,
      selectionConsistencyMode,
      filters,
      search
    });
    (0, _mobx.makeObservable)(this, {
      total: _mobx.computed,
      status: _mobx.computed
    });
  }
  init() {
    var _collection$_optimist;
    const {
      _collection,
      _totalsCollection
    } = this;
    const disposers = [_totalsCollection.init(), (_collection$_optimist = _collection._optimisticActions) == null ? void 0 : _collection$_optimist.initCollection(_totalsCollection), (0, _util.addEventListener)(_collection.emitter, 'search', () => {
      _totalsCollection.clearResultAndMoveToStart();
    }), (0, _util.addEventListener)(_collection.emitter, 'clearSearch', _totalsCollection.clearResultAndMoveToStart), (0, _util.addEventListener)(_collection.emitter, 'refreshAllPages', _totalsCollection.refreshAllPages), (0, _util.addEventListener)(_collection.emitter, 'refreshCurrentPage', _totalsCollection.refreshCurrentPage)];
    return () => {
      disposers.forEach(disposer => disposer == null ? void 0 : disposer());
    };
  }
  get total() {
    return this._totalsCollection.result.total;
  }
  get status() {
    // While refreshing the status remains as success
    return this._totalsCollection.lifecycleState === 'refresh' ? 'loading' : this._totalsCollection.result.status.status;
  }
}
exports.FetchTotalState = FetchTotalState;
//# sourceMappingURL=FetchTotalState.js.map