"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.AppliedFiltersTagListState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _bi = require("@wix/bex-core/bi");
var _mobx = require("mobx");
var _events = require("events");
var _util = require("@wix/bex-core/util");
var _groupBy = _interopRequireDefault(require("lodash/groupBy"));
var _FilterTagContent = require("./FilterTagContent");
var _react = _interopRequireDefault(require("react"));
var _jsxFileName = "/home/builduser/work/843658b9f44192f0/packages/cairo/dist/cjs/components/AppliedFiltersTagList/AppliedFiltersTagListState.tsx";
class AppliedFiltersTagListState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "table", void 0);
    (0, _defineProperty2.default)(this, "events", new _events.EventEmitter());
    (0, _defineProperty2.default)(this, "maxWidth", '408px');
    (0, _defineProperty2.default)(this, "onClearButtonClick", (0, _mobx.action)(() => {
      var _toolbarFiltersState$;
      const {
        table
      } = this;
      const {
        collection,
        toolbarFiltersState
      } = table;
      const {
        query: {
          nonPersistentFilters
        }
      } = collection;
      collection.emitter.emit('beforeClearFilters', {
        origin: 'toolbar'
      });
      nonPersistentFilters.filter(filter => !filter._hideFromToolbar).forEach(filter => {
        filter == null || filter.reset({
          emitEvents: ['change', 'refresh']
        });
      });
      toolbarFiltersState == null || (_toolbarFiltersState$ = toolbarFiltersState.moreFiltersButtonRef) == null || (_toolbarFiltersState$ = _toolbarFiltersState$.current) == null || _toolbarFiltersState$.focus();
    }));
    this.table = params.table;
    (0, _mobx.makeObservable)(this, {
      filterValues: _mobx.computed,
      tags: _mobx.computed,
      filterPropsMap: _mobx.computed
    });
  }
  init() {
    const {
      multi: {
        collections
      }
    } = this.table;
    const disposers = [...collections.map(collection => (0, _util.addEventListener)(collection.emitter, 'fetch', () => {
      const ls = this.events.listeners('fetch').map(l => l(collection));
      return () => {
        ls.forEach(l => l());
      };
    }))];
    return () => {
      disposers.forEach(d => d());
    };
  }
  get filterPropsMap() {
    const {
      table: {
        filtersProps
      }
    } = this;
    return new Map((filtersProps == null ? void 0 : filtersProps.map(filterProps => [filterProps.filter, filterProps])) ?? []);
  }
  toTag(key, filter) {
    var _filterPropsMap$get;
    const {
      filterPropsMap
    } = this;
    const {
      value: filterValue
    } = filter;
    const explodeTags = (_filterPropsMap$get = filterPropsMap.get(filter)) == null ? void 0 : _filterPropsMap$get.explodeTags;
    return filter.toArray.map(value => ({
      id: Array.isArray(filterValue) || explodeTags ? `${key}-${filter.itemKey(value)}` : key,
      filter,
      value
    }));
  }
  get filterValues() {
    const {
      table: {
        activeFiltersEntries
      }
    } = this;
    return activeFiltersEntries.filter(([_, filter]) => !filter._hideFromToolbar).flatMap(([key, filter]) => this.toTag(key, filter));
  }
  get tags() {
    const {
      filterValues,
      filterPropsMap
    } = this;
    const groupedFilters = (0, _groupBy.default)(filterValues, 'filter.name');
    return Object.entries(groupedFilters).flatMap(([_, filterValuesGroup]) => {
      const filterProps = filterPropsMap.get(filterValuesGroup[0].filter);
      if (filterProps != null && filterProps.renderToolbarTag) {
        return this.generateNonAggregatedTag(filterValuesGroup, filterProps);
      }
      return this.generateAggregatedTag(filterValuesGroup, filterProps);
    });
  }
  _reportFilterToggleBiOnNextResult(filter, values) {
    const filterValuesKeys = values.map(value => filter.itemKey(value));
    const {
      table,
      events
    } = this;
    const {
      reportBi
    } = table;
    const onFetch = collection => {
      events.off('fetch', onFetch);
      return (0, _mobx.action)(() => {
        reportBi((0, _bexCore.withoutDefaults)(_bi.cairoFilterToggled)({
          ...table._commonDynamicBiParams(),
          ...collection._commonDynamicBiParams(),
          actionType: 'remove',
          origin: 'sub-toolbar',
          filterName: filter.name,
          filterValue: filterValuesKeys.join(),
          numFiltersActive: collection.query.activeFiltersCount,
          filteredListSize: collection.result.total,
          isCustomField: !!filter.isCustomField
        }));
      });
    };
    events.on('fetch', onFetch);
  }
  onTagRemove(filter, values, onAppliedFilterTagRemove) {
    const {
      table,
      tags
    } = this;
    const isLastTag = tags.length === 1;
    this._reportFilterToggleBiOnNextResult(filter, values);
    filter.remove(values, {
      emitEvents: ['change', 'refresh']
    });
    values.forEach(value => {
      onAppliedFilterTagRemove == null || onAppliedFilterTagRemove(value);
    });
    if (isLastTag) {
      var _table$toolbarFilters;
      (_table$toolbarFilters = table.toolbarFiltersState) == null || (_table$toolbarFilters = _table$toolbarFilters.moreFiltersButtonRef) == null || (_table$toolbarFilters = _table$toolbarFilters.current) == null || _table$toolbarFilters.focus();
    }
  }
  generateNonAggregatedTag(filterValuesGroup, filterProps) {
    return filterValuesGroup.map(({
      id,
      filter,
      value
    }) => {
      return {
        children: filter.itemName(value),
        key: id,
        filterProps,
        id,
        dataHook: id,
        filter,
        values: [value],
        maxWidth: this.maxWidth,
        ...(filterProps == null || filterProps.renderToolbarTag == null ? void 0 : filterProps.renderToolbarTag(value))
      };
    });
  }
  generateAggregatedTag(filterValuesGroup, filterProps) {
    return {
      children: /*#__PURE__*/_react.default.createElement(_FilterTagContent.FilterTagContent, {
        filterProps: filterProps,
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 215,
          columnNumber: 9
        }
      }, filterValuesGroup.map(({
        filter,
        value
      }) => filter.itemName(value)).join(', ')),
      key: filterProps == null ? void 0 : filterProps.filter.name,
      filterProps,
      id: filterProps == null ? void 0 : filterProps.filter.name,
      dataHook: filterProps == null ? void 0 : filterProps.filter.name,
      filter: filterValuesGroup[0].filter,
      values: filterValuesGroup.map(({
        value
      }) => value),
      maxWidth: this.maxWidth
    };
  }
}
exports.AppliedFiltersTagListState = AppliedFiltersTagListState;
//# sourceMappingURL=AppliedFiltersTagListState.js.map