"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.PickerContentState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _util = require("@wix/bex-core/util");
var _MaxSelection = require("../components/MaxSelection");
var _mobx = require("mobx");
var _bi = require("@wix/bex-core/bi");
var _events2 = require("events");
var _PickerContentStateBI = require("./PickerContentStateBI");
const isPickerSelectionV2 = e => e != null && typeof e === 'object' && ('defaultStatus' in e || 'values' in e);
class PickerContentState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "picker", void 0);
    (0, _defineProperty2.default)(this, "modalState", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _bexCore.TaskState());
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "events", new _events2.EventEmitter());
    (0, _defineProperty2.default)(this, "initialSelect", void 0);
    (0, _defineProperty2.default)(this, "additionalStep", void 0);
    (0, _defineProperty2.default)(this, "isAdditionalStepShown", false);
    (0, _defineProperty2.default)(this, "autoAdditionalStepOnInitialSelect", false);
    (0, _defineProperty2.default)(this, "isAutoAdditionalStepPending", true);
    (0, _defineProperty2.default)(this, "onCreateNew", async items => {
      await this.picker.onCreateNew(items);
      this.selectCreatedItems(items);
    });
    (0, _defineProperty2.default)(this, "onCreateNewButtonClick", onClick => {
      const {
        modalState: {
          _isCustomContentVisible
        },
        picker
      } = this;
      onClick == null || onClick({
        onClose: this.onCreateNew
      });
      _isCustomContentVisible.value = true;
      this.reportBi((0, _bi.newItemCreationStart)({
        ...picker._commonDynamicBiParams(),
        numSelectedItems: picker.collection.bulkSelect.select.selectedCount
      }));
    });
    (0, _defineProperty2.default)(this, "_resultUpdated", () => {
      const {
        initialSelect,
        picker
      } = this;
      const {
        collection
      } = picker;
      const {
        bulkSelect,
        result: {
          keyedItems
        }
      } = collection;
      if (typeof initialSelect === 'function') {
        const initialSelectItems = keyedItems.filter(({
          item
        }, index) => initialSelect(item, index));
        bulkSelect.select.syncValues(initialSelectItems, bulkSelect.select.finalStatus);
        return;
      }
    });
    (0, _defineProperty2.default)(this, "toggleIsSelectAll", (0, _mobx.action)(() => {
      const {
        picker,
        events
      } = this;
      const {
        collection: {
          bulkSelect,
          query: {
            hasActiveFilters
          },
          result
        }
      } = picker;
      const {
        allSelected,
        select: {
          isEmpty
        }
      } = bulkSelect;
      const afters = events.listeners('beforeToggleIsSelectAll').map(l => l());
      if (allSelected || !isEmpty) {
        bulkSelect.toggleIsSelectAll();
      } else if (hasActiveFilters) {
        for (const keyedItem of result.keyedItems) {
          bulkSelect.selectOneItem(keyedItem);
        }
      } else {
        bulkSelect.toggleIsSelectAll();
      }
      afters.forEach(({
        afterToggleIsSelectAll
      }) => afterToggleIsSelectAll());
    }));
    const {
      collection: _collection,
      modalState,
      createBILogger,
      events: _events,
      initialSelect: _initialSelect
    } = params;
    this.initialSelect = _initialSelect;
    this.modalState = modalState;
    this.reportBi = createBILogger({
      ..._collection.fqdn,
      type: 'modal',
      componentType: 'Picker Modal',
      artifactId: modalState.environment.artifactId
    });
    this.picker = new _bexCore.PickerState({
      collection: _collection,
      getMaxItems: modalState.getMaxItems,
      shouldFilterNotAffectTotalCount: modalState.shouldFilterNotAffectTotalCount,
      minContentHeight: modalState.minContentHeight,
      events: _events,
      reportBi: this.reportBi
    });
    (0, _mobx.makeObservable)(this, {
      _setInitialSelection: _mobx.action,
      isAdditionalStepShown: _mobx.observable.ref,
      setIsAdditionalStepShown: _mobx.action.bound,
      isAutoAdditionalStepPending: _mobx.observable.ref
    });
    if (modalState.pickerContentRef.current == null) {
      this._setInitialData();
    }
    this._setInitialSelection();
  }
  _setInitialData() {
    const {
      modalState,
      picker
    } = this;
    const {
      collection
    } = picker;
    const {
      firstPageResult
    } = modalState.fetchFirstPage.status.value.data ?? {};
    if (firstPageResult) {
      collection.setInitialPage(firstPageResult);
    }
  }
  _setInitialSelection() {
    const {
      initialSelect,
      picker
    } = this;
    const {
      collection
    } = picker;
    const {
      bulkSelect,
      result: {
        keyedItems,
        itemKey
      }
    } = collection;
    if (initialSelect == null) {
      return;
    }
    if (typeof initialSelect === 'boolean') {
      const [firstItem] = keyedItems;
      if (firstItem) {
        bulkSelect.select.forceSet(firstItem);
      }
      return;
    }
    if (typeof initialSelect === 'function') {
      const initialSelectItems = keyedItems.filter(({
        item
      }, index) => initialSelect(item, index));
      bulkSelect.select.syncValues(initialSelectItems, bulkSelect.select.finalStatus);
      return;
    }
    if (isPickerSelectionV2(initialSelect)) {
      const {
        defaultStatus,
        values
      } = initialSelect;
      if (defaultStatus) {
        bulkSelect.select.defaultStatus = typeof defaultStatus === 'object' ? defaultStatus : _bexCore.selectionStatusWixPatternsPreset[defaultStatus];
      }
      if (values) {
        bulkSelect.select.forceSetMany(values.map(({
          status,
          value
        }) => ({
          value: {
            item: value,
            key: itemKey(value)
          },
          status: typeof status === 'object' ? status : _bexCore.selectionStatusWixPatternsPreset[status]
        })));
      }
      return;
    }
    if (initialSelect.isSelectAll) {
      bulkSelect.selectAll();
      if (initialSelect.uncheckedValues) {
        initialSelect.uncheckedValues.forEach(item => {
          typeof item === 'string' ? bulkSelect.deselectOne(item) : bulkSelect.deselectOneItem({
            key: itemKey(item),
            item
          });
        });
      }
      return;
    }
    if (initialSelect.selectedValues) {
      initialSelect.selectedValues.forEach(item => {
        typeof item === 'string' ? bulkSelect.selectOne(item) : bulkSelect.selectOneItem({
          key: itemKey(item),
          item
        });
      });
    }
    if (initialSelect.partiallySelectedIds) {
      const resolvedEntriesFromCollection = initialSelect.partiallySelectedIds.map(item => {
        const collectionItem = typeof item === 'string' ? bulkSelect.getCollectionItem(item) : {
          key: itemKey(item),
          item
        };
        if (!collectionItem) {
          return null;
        }
        return {
          status: _bexCore.selectionStatusWixPatternsPreset.indeterminate,
          value: {
            key: collectionItem.key,
            item: collectionItem.item
          }
        };
      });
      bulkSelect.select.forceSetMany(resolvedEntriesFromCollection.filter(e => e != null));
    }
  }
  selectCreatedItems(items) {
    const {
      picker,
      modalState: {
        multipleRef
      }
    } = this;
    const {
      collection: {
        bulkSelect,
        itemKey
      }
    } = picker;
    if (items != null && items.length) {
      const [item] = items;
      const multiple = (0, _MaxSelection.fromMultipleSelectionToBoolean)(multipleRef.current);
      if (!multiple) {
        bulkSelect.resetToDefaults();
      }
      bulkSelect.selectOne(itemKey(item));
    }
  }
  _reportFilterToggleBiOnNextResult(params, filter) {
    const {
      actionType,
      clickedValueKey
    } = params ?? {};
    const {
      picker: {
        collection
      }
    } = this;
    const onFetch = () => {
      collection.emitter.off('fetch', onFetch);
      return (0, _mobx.action)(() => {
        this.reportBi((0, _bexCore.withoutDefaults)(_bi.cairoFilterToggled)({
          ...this.picker._commonDynamicBiParams(),
          origin: 'Picker Modal',
          filterValue: clickedValueKey,
          filterName: filter.name,
          actionType,
          numFiltersActive: collection.query.activeFiltersCount,
          filteredListSize: collection.result.total,
          isCustomField: !!filter.isCustomField
        }));
      });
    };
    this.picker.collection.emitter.on('fetch', onFetch);
  }
  init(initParams) {
    const {
      picker,
      modalState,
      initTask
    } = this;
    const {
      collection
    } = picker;
    if (initParams != null && initParams.autoAdditionalStepOnInitialSelect) {
      this.autoAdditionalStepOnInitialSelect = true;
    } else {
      this.isAutoAdditionalStepPending = false;
    }
    const bi = new _PickerContentStateBI.PickerContentStateBI({
      state: this
    });
    const disposers = [picker.init(), bi.init()];
    this.picker.collection.query.filtersArray.forEach(filter => {
      disposers.push((0, _util.addEventListener)(filter.events, 'change', params => {
        this._reportFilterToggleBiOnNextResult(params, filter);
      }));
    });
    collection.emitter.on('resultUpdated', this._resultUpdated);
    modalState.pickerContentRef.current = {
      onCreateNew: this.onCreateNew
    };
    initTask.run(async () => {
      await picker.initTask.status.promise;
      if (!isPickerSelectionV2(this.initialSelect)) {
        this._setInitialSelection();
      }
      if (this.autoAdditionalStepOnInitialSelect) {
        (0, _mobx.runInAction)(() => {
          var _this$picker$collecti;
          const selectedItem = (_this$picker$collecti = this.picker.collection.bulkSelect.selectedValues) == null ? void 0 : _this$picker$collecti[0];
          if (selectedItem) {
            this.isAdditionalStepShown = true;
          }
          this.isAutoAdditionalStepPending = false;
        });
      }
    });
    return () => {
      const {
        current: pickerContent
      } = modalState.pickerContentRef;
      if (pickerContent) {
        pickerContent.onCreateNew = undefined;
      }
      disposers.forEach(d => d());
      picker.collection.emitter.off('resultUpdated', this._resultUpdated);
    };
  }
  setIsAdditionalStepShown(value) {
    this.isAdditionalStepShown = value;
  }
}
exports.PickerContentState = PickerContentState;
//# sourceMappingURL=PickerContentState.js.map