"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.CollectionViewsState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _ViewsState = require("./ViewsState");
var _mobx = require("mobx");
var _CollectionViewsStateBIReporter = require("./CollectionViewsStateBIReporter");
var _events = require("events");
var _indexOfCompareFn = require("./indexOfCompareFn");
var _CollectionViewsQueryCompareHelper = require("./CollectionViewsQueryCompareHelper");
var _ViewsHistoryState = require("./ViewsHistoryState");
class CollectionViewsState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "views", void 0);
    (0, _defineProperty2.default)(this, "table", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _bexCore.TaskState());
    (0, _defineProperty2.default)(this, "emitter", new _events.EventEmitter());
    (0, _defineProperty2.default)(this, "queryCompareHelper", void 0);
    (0, _defineProperty2.default)(this, "onDeleteView", void 0);
    (0, _defineProperty2.default)(this, "onSaveViewChanges", void 0);
    (0, _defineProperty2.default)(this, "onSaveView", void 0);
    (0, _defineProperty2.default)(this, "onRenameView", void 0);
    (0, _defineProperty2.default)(this, "onSetAsDefaultView", void 0);
    (0, _defineProperty2.default)(this, "learnMoreLink", void 0);
    (0, _defineProperty2.default)(this, "viewNamePlaceholder", void 0);
    (0, _defineProperty2.default)(this, "viewsStateBIReporter", void 0);
    this.table = params.table;
    this.onDeleteView = params.onDeleteView;
    this.onSaveViewChanges = params.onSaveViewChanges;
    this.onSaveView = params.onSaveView;
    this.onRenameView = params.onRenameView;
    this.onSetAsDefaultView = params.onSetAsDefaultView;
    this.learnMoreLink = params.learnMoreLink;
    this.viewNamePlaceholder = params.viewNamePlaceholder;
    this.views = new _ViewsState.ViewsState({
      oldNamespace: this.table.namespace,
      container: params.container,
      presets: params.presets,
      fqdn: this.table.collection.queryName,
      allItemsViewProps: params.allItemsViewProps,
      reportBI: this.table.reportBi
    });
    this.views._migrateOrdersViews = viewsState => {
      var _migrateOrdersViews, _ref;
      (_migrateOrdersViews = (_ref = this.table.collection)._migrateOrdersViews) == null || _migrateOrdersViews.call(_ref, viewsState);
    };
    this.views._fixMissingContactsViews = viewsState => {
      var _fixMissingContactsVi, _ref2;
      (_fixMissingContactsVi = (_ref2 = this.table.collection)._fixMissingContactsViews) == null || _fixMissingContactsVi.call(_ref2, viewsState);
    };
    this.queryCompareHelper = new _CollectionViewsQueryCompareHelper.CollectionViewsQueryCompareHelper({
      table: this.table,
      collectionViews: this
    });
    this.viewsStateBIReporter = new _CollectionViewsStateBIReporter.CollectionViewsStateBIReporter({
      reportBI: this.table.reportBi,
      collectionViewState: this
    });
    (0, _mobx.makeObservable)(this, {
      _setSelectedViewToCollectionQuery: _mobx.action.bound,
      _onSelectViewAndRefresh: _mobx.action.bound,
      _selectInitialView: _mobx.action.bound,
      isViewChanged: _mobx.computed,
      currentViewColumns: _mobx.computed,
      currentViewColumnsOrDefaultColumns: _mobx.computed
    });
  }
  get isViewChanged() {
    const {
      views: {
        currentView
      }
    } = this;
    return !currentView || this.queryCompareHelper.isSelectedColumnsChanged || this.queryCompareHelper.isSortChanged || this.queryCompareHelper.isFiltersChanged;
  }
  get _doNotWaitForViewsExperimentEnabled() {
    const {
      table: {
        container: {
          experiments,
          internalExperiments
        }
      }
    } = this;
    return (internalExperiments == null ? void 0 : internalExperiments.enabled('specs.cairo.doNotWaitForViews')) || experiments.enabled('specs.cairo.stores.doNotWaitForViews');
  }
  init() {
    const {
      views,
      initTask,
      table: {
        collection,
        container: {
          history
        }
      }
    } = this;
    if (this._doNotWaitForViewsExperimentEnabled) {
      this._selectInitialView(views._getAllItemsAndPresetViews());
    }
    const disposers = [(0, _bexCore.addEventListener)(collection.hooks, 'beforeInitialFetch', (0, _mobx.action)(async () => {
      if (!this._doNotWaitForViewsExperimentEnabled && !collection.query._initializedFromHistory) {
        var _this$initTask$status;
        await ((_this$initTask$status = this.initTask.status.promise) == null ? void 0 : _this$initTask$status.catch(() => {}));
      }
    })), views.init(), ...this._subscribeOnSelectView(), ...this._subscribeOnViewAction(), this.viewsStateBIReporter.init(), new _ViewsHistoryState.ViewsHistoryState({
      views: this.views,
      history
    }).init()];
    initTask.runOnce(async () => {
      await views.initTask.status.promise;
      (0, _mobx.runInAction)(() => {
        if (this._selectInitialView(views.collection.result.items)) {
          // when not waiting for views, we need to refresh the collection as the initialView after views loaded might have changed the query
          if (this._doNotWaitForViewsExperimentEnabled) {
            this.table.collection.clearResultAndMoveToStart();
          }
        }
      });
    });
    return () => {
      disposers.forEach(disposer => disposer());
    };
  }
  _selectInitialView(items) {
    const {
      views,
      table: {
        collection
      }
    } = this;
    if (this.views.currentView) {
      return;
    }
    const initialSelectItem = views._getInitialSelectItem(items);
    if (initialSelectItem == null) {
      return;
    }
    if (!views._initialViewIdFromUrl && collection.query._initializedFromHistory) {
      return;
    }
    const view = views.getView(initialSelectItem.id);
    views.currentView = view ?? null;
    if (!collection.query._initializedFromHistory) {
      this._setSelectedViewToCollectionQuery();
      return true;
    }
  }
  _subscribeOnViewAction() {
    const {
      views
    } = this;
    return [(0, _bexCore.addEventListener)(views.events, 'undoAction', this.viewsStateBIReporter.undoActionBI.bind(this.viewsStateBIReporter)), (0, _bexCore.addEventListener)(views.events, 'tryAgainAction', this.viewsStateBIReporter.tryAgainBI.bind(this.viewsStateBIReporter)), (0, _bexCore.addEventListener)(views.events, 'errorAction', this.viewsStateBIReporter.errorBI.bind(this.viewsStateBIReporter))];
  }
  _subscribeOnSelectView() {
    const {
      views
    } = this;
    return [(0, _bexCore.addEventListener)(views.events, 'selectAndRefresh', (0, _mobx.action)(this._onSelectViewAndRefresh))];
  }
  _onSelectViewAndRefresh(needFiltersReset = true) {
    if (!needFiltersReset) {
      return;
    }
    const {
      table: {
        collection
      }
    } = this;
    const {
      query
    } = collection;
    this._setSelectedViewToCollectionQuery();
    query.events.emit('refresh');
  }
  get currentViewColumns() {
    const {
      views,
      table
    } = this;
    const {
      columns,
      customColumnsState
    } = table;
    const {
      currentView
    } = views;
    const viewSelectedColumns = currentView == null ? void 0 : currentView.selectedColumns;
    if (!(viewSelectedColumns != null && viewSelectedColumns.length)) {
      return null;
    }
    const selectedColumnsToSet = columns.map(({
      id,
      hideable,
      hiddenFromCustomColumnsSelection
    }) => ({
      id,
      isSelected: viewSelectedColumns.some(c => c.id === id && c.isSelected !== false) || !hideable || hiddenFromCustomColumnsSelection === true
    }));
    return customColumnsState != null && customColumnsState.dragAndDrop ? selectedColumnsToSet.sort((0, _indexOfCompareFn.indexOfCompareFn)(viewSelectedColumns, e => e == null ? void 0 : e.id)) : selectedColumnsToSet;
  }
  get currentViewColumnsOrDefaultColumns() {
    return this.currentViewColumns ?? this.table.selectedColumns.defaultValue;
  }
  _setSelectedViewToCollectionQuery() {
    const {
      views,
      table
    } = this;
    const {
      selectedColumns,
      collection
    } = table;
    const {
      currentView
    } = views;
    const {
      query
    } = collection;
    query.resetFilters();
    if (currentView != null && currentView.filters) {
      Object.entries(currentView.filters).forEach(([filterName, filter]) => {
        const queryFilter = query.filters[filterName];
        if (queryFilter && queryFilter.value !== (filter == null ? void 0 : filter.value)) {
          queryFilter.setValue(queryFilter.decode(filter == null ? void 0 : filter.value));
        }
      });
    }
    query.resetSorting();
    if (currentView != null && currentView.sortDirections && currentView.sortDirections.length > 0) {
      query.sort.setSortQuery(currentView.sortDirections.map(sortInView => ({
        field: sortInView.columnId,
        direction: sortInView.direction === 'Ascending' ? 'asc' : 'desc'
      })), {
        emitChangeEvent: true
      });
    } else {
      query.resetSorting({
        emitChangeEvent: true
      });
    }
    if (this.currentViewColumns) {
      selectedColumns.setValue(this.currentViewColumns);
    } else {
      selectedColumns.reset();
    }
    query.setExtra(currentView == null ? void 0 : currentView.extra);
  }
  async deleteView(view) {
    try {
      var _this$onDeleteView;
      const viewToDelete = view ?? this.views.currentView;
      if (!viewToDelete) {
        return;
      }
      this.viewsStateBIReporter.deleteViewSelectedBI();
      (_this$onDeleteView = this.onDeleteView) == null || _this$onDeleteView.call(this, viewToDelete);
      await this.views.deleteView(viewToDelete);
      this.viewsStateBIReporter.deleteViewBI(viewToDelete);
    } catch (e) {
      throw new _bexCore.WixPatternsError({
        originalException: e,
        errorCode: 'DeleteViewFailed'
      });
    }
  }
  async saveViewChanges() {
    this.viewsStateBIReporter.saveViewChangesSelectedBI();
    const oldView = this.views.currentView ? {
      ...this.views.currentView
    } : undefined;
    const newView = await this.views.saveViewChanges(this.queryCompareHelper.currentViewBase);
    if (newView) {
      var _this$onSaveViewChang;
      (_this$onSaveViewChang = this.onSaveViewChanges) == null || _this$onSaveViewChang.call(this, newView);
      this.viewsStateBIReporter.saveViewChangesBI(newView, oldView);
    }
  }
  sendSaveNewViewSelectedBI() {
    this.viewsStateBIReporter.saveNewViewSelectedBI();
  }
  async saveNewView(name) {
    try {
      var _this$views$currentVi, _this$onSaveView;
      const newView = await this.views.saveView({
        newView: this.views.createNewView(name, this.queryCompareHelper.currentViewBase),
        isNew: true,
        oldViewId: (_this$views$currentVi = this.views.currentView) == null ? void 0 : _this$views$currentVi.id
      });
      (_this$onSaveView = this.onSaveView) == null || _this$onSaveView.call(this, newView);
      this.viewsStateBIReporter.saveNewViewBI(newView);
    } catch (err) {
      throw new _bexCore.WixPatternsError({
        errorCode: 'SaveViewFailed',
        originalException: err
      });
    }
  }
  sendRenameViewSelectedBI() {
    this.viewsStateBIReporter.renameViewSelectedBI();
  }
  async renameView(name) {
    try {
      var _this$views$currentVi2, _this$onRenameView;
      if (!this.views.currentView) {
        return;
      }
      const oldName = this.views.currentView.name;
      const newView = await this.views.renameView({
        ...this.views.currentView,
        name
      }, ((_this$views$currentVi2 = this.views.currentView) == null ? void 0 : _this$views$currentVi2.name) ?? '');
      (_this$onRenameView = this.onRenameView) == null || _this$onRenameView.call(this, newView);
      this.viewsStateBIReporter.renameViewBI(newView, oldName);
    } catch (e) {
      throw new _bexCore.WixPatternsError({
        originalException: e,
        errorCode: 'RenameViewFailed'
      });
    }
  }
  async setAsDefaultView() {
    try {
      var _this$onSetAsDefaultV;
      if (!this.views.currentView) {
        return;
      }
      const isDefault = this.views.defaultViewId !== this.views.currentView.id;
      this.viewsStateBIReporter.setAsDefaultViewSelectedBI(isDefault);
      const newView = await this.views.setAsDefaultView(this.views.currentView, isDefault);
      (_this$onSetAsDefaultV = this.onSetAsDefaultView) == null || _this$onSetAsDefaultV.call(this, newView, isDefault);
      this.viewsStateBIReporter.setAsDefaultViewBI(isDefault, newView);
    } catch (e) {
      throw new _bexCore.WixPatternsError({
        originalException: e,
        errorCode: 'SetAsDefaultViewFailed'
      });
    }
  }
}
exports.CollectionViewsState = CollectionViewsState;
//# sourceMappingURL=CollectionViewsState.js.map