"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.QueryState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _Pagination = require("./Pagination");
var _mapValues = _interopRequireDefault(require("lodash/mapValues"));
var _pickBy = _interopRequireDefault(require("lodash/pickBy"));
var _events = require("events");
var _StringFilterState = require("./StringFilterState");
var _SortState = require("./SortState");
var _util = require("../util");
var _core = require("react-query/core");
var _QueryHistoryState = require("./QueryHistoryState");
class QueryState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "history", void 0);
    (0, _defineProperty2.default)(this, "pagination", void 0);
    (0, _defineProperty2.default)(this, "customFilters", void 0);
    (0, _defineProperty2.default)(this, "sort", void 0);
    (0, _defineProperty2.default)(this, "_filters", void 0);
    (0, _defineProperty2.default)(this, "events", new _events.EventEmitter());
    (0, _defineProperty2.default)(this, "queryHistory", void 0);
    (0, _defineProperty2.default)(this, "refreshOnColumnsChange", void 0);
    (0, _defineProperty2.default)(this, "_columns", _mobx.observable.set([], {
      deep: false
    }));
    (0, _defineProperty2.default)(this, "_fields", _mobx.observable.set([], {
      deep: false
    }));
    (0, _defineProperty2.default)(this, "_initializedFromHistory", void 0);
    (0, _defineProperty2.default)(this, "_skipFilterListeners", void 0);
    (0, _defineProperty2.default)(this, "addFilterListeners", filter => {
      if (this._skipFilterListeners) {
        return [];
      }
      return [(0, _util.addEventListener)(filter.events, 'change', () => this.events.emit('change')), (0, _util.addEventListener)(filter.events, 'refresh', () => this.events.emit('refresh')), (0, _util.addEventListener)(filter.events, 'scheduleRefresh', () => this.events.emit('scheduleRefresh'))];
    });
    this.refreshOnColumnsChange = params.refreshOnColumnsChange;
    this.pagination = new _Pagination.Pagination({
      limit: params.limit
    });
    this.history = params.history;
    this.sort = new _SortState.SortState({});
    this.customFilters = (0, _mapValues.default)(params.filters, (filter, name) => {
      if (filter) {
        filter.name = name;
      }
      return filter;
    });
    this._filters = {
      ...this.customFilters,
      search: params.search ?? new _StringFilterState.StringFilterState({
        name: 'search',
        defaultValue: ''
      })
    };
    this.queryHistory = this.history ? new _QueryHistoryState.QueryHistoryState({
      query: this,
      history: this.history
    }) : null;
    (0, _mobx.makeObservable)(this, {
      changeLimit: _mobx.action,
      reset: _mobx.action,
      toComputed: _mobx.action,
      _filters: _mobx.observable.ref,
      customFilters: _mobx.observable.ref,
      addFilterIfNeeded: _mobx.action,
      asComputed: _mobx.computed,
      activeFilters: _mobx.computed,
      nonPersistentFilters: _mobx.computed,
      nonPersistentFiltersEntries: _mobx.computed,
      nonPersistentFiltersMap: _mobx.computed,
      activeFiltersEntries: _mobx.computed,
      activeFiltersCount: _mobx.computed,
      hasActiveFilters: _mobx.computed,
      hasNonPersistentActiveFilters: _mobx.computed,
      resetFilters: _mobx.action.bound,
      resetPage: _mobx.action.bound,
      filtersKey: _mobx.computed,
      filtersKeyHash: _mobx.computed,
      fields: _mobx.computed,
      fieldsKey: _mobx.computed,
      fieldsKeyHash: _mobx.computed,
      hasNonPersistentCustomFilters: _mobx.computed,
      nonPersistentCustomFiltersCount: _mobx.computed
    });
  }
  init({
    skipFilterListeners
  } = {}) {
    var _this$queryHistory;
    this._skipFilterListeners = skipFilterListeners;
    const disposers = [...Object.values(this.filtersEntries).flatMap(([_, filter]) => {
      return this.addFilterListeners(filter);
    }), (_this$queryHistory = this.queryHistory) == null ? void 0 : _this$queryHistory.init()];
    return () => {
      disposers.forEach(d => d == null ? void 0 : d());
    };
  }
  get limit() {
    return this.pagination.limit;
  }
  get fields() {
    return [...Array.from(this._columns.values()), ...Array.from(this._fields.values())];
  }
  get fieldsKey() {
    return this.fields.sort();
  }
  get fieldsKeyHash() {
    return this.fieldsKey.join('');
  }
  get filtersKey() {
    const {
      customFilters
    } = this;
    return (0, _mapValues.default)(customFilters, filter => filter != null ? filter.isEmpty ? null : filter.toArray.map(filter.itemKey) : undefined);
  }
  get filtersKeyHash() {
    return (0, _core.hashQueryKey)([this.filtersKey]);
  }
  changeLimit(limit) {
    this.pagination.changeLimit(limit);
  }
  reset() {
    this.pagination.moveToPage(0);
  }
  _toComputed() {
    const {
      pagination,
      customFilters,
      nonPersistentFiltersMap,
      search: searchFilter,
      sort,
      hasActiveFilters,
      hasNonPersistentActiveFilters,
      fields,
      refreshOnColumnsChange
    } = this;
    const {
      page,
      limit,
      offset,
      cursor
    } = pagination;
    const filters = (0, _mapValues.default)(customFilters, filter => filter != null ? filter.isEmpty ? undefined : filter.value : filter);
    const rawFilters = (0, _mapValues.default)(customFilters, filter => filter != null ? filter.value : filter);
    const filtersKey = (0, _mapValues.default)(customFilters, filter => filter != null ? filter.isEmpty ? null : filter.toArray.map(filter.itemKey) : undefined);
    const nonPersistentFiltersKey = (0, _mapValues.default)(nonPersistentFiltersMap, filter => filter != null ? filter.isEmpty ? null : filter.toArray.map(filter.itemKey) : undefined);
    const rawSearch = searchFilter.value;
    const search = searchFilter.isEmpty ? undefined : rawSearch;
    return {
      page,
      limit,
      sort: sort.value.map(({
        field: fieldName,
        direction: order
      }) => ({
        fieldName,
        order
      })),
      offset,
      cursor: cursor == null || typeof cursor === 'string' ? cursor : null,
      rawFilters,
      filtersKey,
      nonPersistentFiltersKey,
      filters,
      rawSearch,
      search,
      hasActiveFilters,
      hasNonPersistentActiveFilters,
      columns: fields,
      fields: refreshOnColumnsChange ? fields : Array.from(this._fields.values())
    };
  }
  toComputed() {
    return this._toComputed();
  }
  get asComputed() {
    return this._toComputed();
  }
  get filtersArray() {
    const {
      _filters
    } = this;
    return Object.values(_filters).filter(e => e != null);
  }
  get nonPersistentFilters() {
    const {
      filtersArray
    } = this;
    return filtersArray.filter(filter => !filter.persistent);
  }
  get filtersEntries() {
    const {
      _filters
    } = this;
    return Object.entries(_filters).filter(entry => entry[1] != null);
  }
  get nonPersistentFiltersEntries() {
    const {
      filtersEntries
    } = this;
    return filtersEntries.filter(([_, filter]) => !filter.persistent);
  }
  get nonPersistentCustomFiltersCount() {
    return Object.values(this.nonPersistentCustomFilters).reduce((size, filter) => size + filter.size, 0);
  }
  get hasNonPersistentCustomFilters() {
    return this.nonPersistentCustomFiltersCount > 0;
  }
  get nonPersistentCustomFilters() {
    const {
      customFilters
    } = this;
    return Object.values(customFilters).filter(e => e != null && !(e != null && e.persistent));
  }
  get nonPersistentFiltersMap() {
    const {
      customFilters
    } = this;
    return (0, _pickBy.default)(customFilters, filter => !(filter != null && filter.persistent));
  }
  get activeFiltersEntries() {
    const {
      nonPersistentFiltersEntries
    } = this;
    return nonPersistentFiltersEntries.filter(([_, filter]) => !filter.isEmpty);
  }
  get activeFilters() {
    const {
      nonPersistentFilters
    } = this;
    return nonPersistentFilters.filter(filter => !filter.isEmpty);
  }
  get activeFiltersCount() {
    return this.activeFilters.reduce((size, filter) => size + filter.size, 0);
  }
  get hasActiveFilters() {
    return this.filtersArray.reduce((size, filter) => size + filter.size, 0) > 0;
  }
  get hasNonPersistentActiveFilters() {
    return this.activeFiltersCount > 0;
  }
  get hasActiveSort() {
    return this.sort.value.length > 0;
  }
  addFilterIfNeeded(key, filter) {
    if (filter === undefined || this._filters[key]) {
      return;
    }
    this._filters = {
      ...this._filters,
      [key]: filter
    };
    this.customFilters = {
      ...this.customFilters,
      [key]: filter
    };
    const disposers = this.addFilterListeners(filter);
    return () => {
      disposers.forEach(d => d == null ? void 0 : d());
    };
  }
  resetFilters(options) {
    const {
      nonPersistentFilters
    } = this;
    nonPersistentFilters.forEach(filter => {
      filter == null || filter.reset(options);
    });
  }
  resetCustomFilters(options) {
    const {
      nonPersistentCustomFilters
    } = this;
    nonPersistentCustomFilters.forEach(filter => {
      filter == null || filter.reset(options);
    });
  }
  resetSorting(params = {}) {
    this.sort.reset(params);
  }
  resetPage() {
    const {
      pagination
    } = this;
    pagination.page = 1;
    pagination.cursor = _Pagination.initialCursor;
  }
  get search() {
    return this._filters.search;
  }
  get filters() {
    return this._filters;
  }
}
exports.QueryState = QueryState;
//# sourceMappingURL=QueryState.js.map