"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.PickerState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _TaskState = require("./TaskState");
var _v = require("@wix/bex-utils/@wix/bi-logger-os-data/v2");
var _util = require("../util");
var _snapshot = require("./snapshot");
var _MultiCollectionSupport = require("./MultiCollectionSupport");
var _onItemsCreated = require("./onItemsCreated");
const DEFAULT_FLOATING_NOTIFICATION_HEIGHT = 54;
const withoutDefaults = (0, _util.withoutIrrelevant)();
class PickerState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "collection", void 0);
    (0, _defineProperty2.default)(this, "multi", void 0);
    (0, _defineProperty2.default)(this, "shouldFilterNotAffectTotalCount", void 0);
    (0, _defineProperty2.default)(this, "events", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _TaskState.TaskState());
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "loadStartTime", void 0);
    (0, _defineProperty2.default)(this, "isScrollTop", void 0);
    (0, _defineProperty2.default)(this, "minContentHeight", void 0);
    (0, _defineProperty2.default)(this, "floatingNotificationHeight", 0);
    (0, _defineProperty2.default)(this, "getMaxItems", void 0);
    (0, _defineProperty2.default)(this, "filteredListSize", void 0);
    (0, _defineProperty2.default)(this, "onNewPage", () => {
      const {
        reportBi
      } = this;
      const startTime = performance.now();
      return ({
        totalNewItems
      }) => {
        reportBi(withoutDefaults(_v.loadMore)({
          ...this._commonDynamicBiParams(),
          loadingTime: Math.round(performance.now() - startTime),
          loadedItems: totalNewItems
        }));
      };
    });
    (0, _defineProperty2.default)(this, "onSearchStart", () => {
      const {
        collection,
        reportBi
      } = this;
      const {
        result
      } = collection;
      const startTime = performance.now();
      reportBi((0, _v.pickerModalUsability)({
        ...this._commonDynamicBiParams(),
        action: 'search',
        searchTerm: collection.query.search.value
      }));
      return () => {
        reportBi((0, _v.cairoSearchResults)({
          ...this._commonDynamicBiParams(),
          loadingTime: Math.round(performance.now() - startTime),
          searchResultsCnt: result.total,
          searchTerm: collection.query.search.value
        }));
      };
    });
    (0, _defineProperty2.default)(this, "_onButtonClick", ({
      ctaName,
      currentLevel,
      numLevels
    }) => {
      this.reportBi((0, _v.cairoCtaClicked)({
        ...this._commonDynamicBiParams(),
        ctaIndex: 1,
        numCtas: 1,
        currentLevel,
        numLevels,
        location: 'picker',
        moreActionsIndex: 0,
        ctaName,
        url: typeof window !== 'undefined' ? window.location.href : ''
      }));
    });
    (0, _defineProperty2.default)(this, "onCreateNew", (0, _mobx.action)(async items => {
      if (items) {
        await (0, _onItemsCreated.onItemsCreated)(this.collection, {
          items,
          reportBi: reportProps => {
            this.reportBi({
              ...reportProps,
              params: {
                ...this._commonDynamicBiParams(),
                ...reportProps.params
              }
            });
          }
        });
      } else {
        (0, _mobx.runInAction)(() => {
          this.reportBi((0, _v.newItemCreationEnd)({
            ...this._commonDynamicBiParams(),
            numSelectedItems: this.collection.bulkSelect.select.selectedCount,
            resultType: 'dismissed'
          }));
        });
      }
    }));
    this.getMaxItems = params.getMaxItems;
    this.collection = params.collection;
    this.reportBi = params.reportBi;
    this.multi = new _MultiCollectionSupport.MultiCollectionSupport({
      collections: [this.collection]
    });
    this.shouldFilterNotAffectTotalCount = params.shouldFilterNotAffectTotalCount ?? (() => false);
    this.isScrollTop = true;
    this.minContentHeight = params.minContentHeight ?? 300;
    this.events = params.events ?? {};
    this.loadStartTime = params.loadStartTime ?? performance.now();
    this.filteredListSize = new _snapshot.Snapshot({
      expression: () => Object.values(this.collection.query.customFilters).map(f => f == null ? void 0 : f.value),
      effect: () => this.collection.result.total
    });
    (0, _mobx.makeObservable)(this, {
      setFloatingNotificationHeight: _mobx.action,
      toggle: _mobx.action,
      updateIsScrollTop: _mobx.action,
      onPrimaryButtonClick: _mobx.action,
      isScrollTop: _mobx.observable.ref
    });
  }
  async clearResultAndMoveToStart({
    force
  } = {}) {
    await Promise.all([this.collection.clearResultAndMoveToStart({
      force
    })]);
  }
  updateIsScrollTop(newValue) {
    this.isScrollTop = newValue;
  }
  _commonDynamicBiParams() {
    const {
      collection,
      filteredListSize
    } = this;
    return {
      ...collection._commonDynamicBiParams(),
      listSize: collection.result.total,
      filteredListSize: filteredListSize.value,
      maxItems: this.getMaxItems()
    };
  }
  init() {
    const {
      collection,
      initTask,
      events: {
        onReady,
        onInitialFetchError
      },
      reportBi,
      filteredListSize
    } = this;
    collection.emitter.on('newPageStart', this.onNewPage);
    collection.emitter.on('searchStart', this.onSearchStart);
    const disposers = [collection.init(), filteredListSize.init()];
    initTask.runOnce(async () => {
      const {
        result,
        query
      } = collection;
      try {
        await Promise.all([collection.initTask.status.promise]);
        filteredListSize.forceUpdate();
        (0, _mobx.runInAction)(() => {
          try {
            reportBi(withoutDefaults(_v.loadEnd)({
              ...this._commonDynamicBiParams(),
              url: typeof window !== 'undefined' ? window.location.href : '',
              route: typeof window !== 'undefined' ? window.location.pathname : '',
              loadingTime: Math.round(performance.now() - this.loadStartTime),
              initialItems: result.size
            }));
            onReady == null || onReady({
              query: query.asComputed,
              result: result.asComputed
            });
          } catch (e) {
            collection.errorMonitor.captureException(e);
          }
        });
      } catch (err) {
        await (onInitialFetchError == null ? void 0 : onInitialFetchError({
          err,
          isOnline: collection.onlineState.isOnline
        }));
        throw err;
      }
    });
    return () => {
      collection.emitter.off('newPageStart', this.onNewPage);
      collection.emitter.off('searchStart', this.onSearchStart);
      for (const disposer of disposers) {
        disposer();
      }
    };
  }
  onCloseButtonClick() {
    const {
      reportBi
    } = this;
    reportBi(withoutDefaults(_v.componentDismissed)({
      origin: 'X button'
    }));
  }
  onBackButtonClick() {
    const {
      _onButtonClick
    } = this;
    _onButtonClick({
      ctaName: 'back',
      numLevels: 2,
      currentLevel: 2
    });
  }
  onContinueButtonClick() {
    const {
      _onButtonClick
    } = this;
    _onButtonClick({
      ctaName: 'continue-next',
      numLevels: 2,
      currentLevel: 1
    });
  }
  onSecondaryButtonOnClick() {
    const {
      reportBi
    } = this;
    reportBi(withoutDefaults(_v.componentDismissed)({
      origin: 'Cancel button'
    }));
  }
  onPrimaryButtonClick({
    currentLevel,
    numLevels
  }) {
    const {
      collection: {
        bulkSelect
      },
      _onButtonClick,
      reportBi
    } = this;
    const {
      selectedCount
    } = bulkSelect;
    _onButtonClick({
      ctaName: 'continue',
      currentLevel,
      numLevels
    });
    reportBi((0, _v.pickerPickModalCtaButtonClickOrImmediateCta)({
      ...this._commonDynamicBiParams(),
      isImmediate: false,
      itemsCnt: selectedCount
    }));
  }
  toggle(keyedItem, options = {}) {
    var _bulkSelect$getCollec;
    const {
      collection,
      events: {
        onItemSelectClick
      },
      reportBi
    } = this;
    const {
      bulkSelect,
      query: {
        search
      }
    } = collection;
    const {
      select,
      selectedCountOrTotal: numItemsBefore
    } = bulkSelect;
    const {
      selectedValues: [prevSelected]
    } = select;
    if (options.clear) {
      bulkSelect.select.clear();
    }
    bulkSelect.toggle(keyedItem);
    reportBi((0, _v.cairoItemSelectionToggled)({
      ...this._commonDynamicBiParams(),
      url: typeof window !== 'undefined' ? window.location.href : '',
      isSelectAll: false,
      isFromSearch: !search.isEmpty,
      searchQuery: search.value,
      itemIndex: keyedItem.index,
      numLevels: options.hasAdditionalStep ? 2 : 1,
      itemId: keyedItem.key,
      clickType: bulkSelect.isChecked(keyedItem.key) ? 'Selection' : 'Deselection',
      numItemsBefore,
      numItemsAfter: bulkSelect.selectedCountOrTotal
    }));
    onItemSelectClick == null || onItemSelectClick({
      item: keyedItem.item,
      index: keyedItem.index,
      previousIndex: prevSelected != null ? (_bulkSelect$getCollec = bulkSelect.getCollectionItem(prevSelected.key)) == null ? void 0 : _bulkSelect$getCollec.index : null
    });
  }
  setFloatingNotificationHeight(floatingNotificationHeight = DEFAULT_FLOATING_NOTIFICATION_HEIGHT) {
    this.floatingNotificationHeight = floatingNotificationHeight;
  }
}
exports.PickerState = PickerState;
//# sourceMappingURL=PickerState.js.map