"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.PickerModalState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _bexUtils = require("@wix/bex-utils");
var _mapValues = _interopRequireDefault(require("lodash/mapValues"));
var _some = _interopRequireDefault(require("lodash/some"));
var _bi = require("@wix/bex-core/bi");
class PickerModalState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "multipleRef", {});
    (0, _defineProperty2.default)(this, "pickerContentRef", {});
    (0, _defineProperty2.default)(this, "onSelectRef", {});
    (0, _defineProperty2.default)(this, "disableAutoSelectionRef", {});
    (0, _defineProperty2.default)(this, "bi", void 0);
    (0, _defineProperty2.default)(this, "_isModalOpen", void 0);
    (0, _defineProperty2.default)(this, "_isCustomContentVisible", (0, _bexUtils.reactive)(false));
    (0, _defineProperty2.default)(this, "_customContent", (0, _bexUtils.reactive)(undefined));
    (0, _defineProperty2.default)(this, "_isOpenButtonClicked", (0, _bexUtils.reactive)(false));
    (0, _defineProperty2.default)(this, "fetchFirstPage", void 0);
    (0, _defineProperty2.default)(this, "fetchPickerComponent", void 0);
    (0, _defineProperty2.default)(this, "fetchInitialProps", void 0);
    (0, _defineProperty2.default)(this, "minContentHeight", void 0);
    (0, _defineProperty2.default)(this, "shouldFilterNotAffectTotalCount", void 0);
    (0, _defineProperty2.default)(this, "queryName", void 0);
    (0, _defineProperty2.default)(this, "fetchData", void 0);
    (0, _defineProperty2.default)(this, "limit", void 0);
    (0, _defineProperty2.default)(this, "_paginationModeRef", {});
    (0, _defineProperty2.default)(this, "events", void 0);
    (0, _defineProperty2.default)(this, "filters", void 0);
    (0, _defineProperty2.default)(this, "environment", void 0);
    (0, _defineProperty2.default)(this, "prefetch", async () => {
      try {
        await Promise.all([this.fetchPickerComponent.once(), this.fetchFirstPage.once(), this.fetchInitialProps.once()]);
        return true;
      } catch (e) {
        console.error(e);
        return false;
      }
    });
    (0, _defineProperty2.default)(this, "hover", () => {
      this.bi.report((0, _bi.pickerPickerOpenButton)({
        action: 'hover',
        ...this._commonDynamicBiParams()
      }));
      this.prefetch();
    });
    (0, _defineProperty2.default)(this, "onCreateNew", async items => {
      var _pickerContentRef$cur;
      const {
        pickerContentRef,
        _isCustomContentVisible
      } = this;
      (_pickerContentRef$cur = pickerContentRef.current) == null || _pickerContentRef$cur.onCreateNew == null || _pickerContentRef$cur.onCreateNew(items);
      if (_isCustomContentVisible.value) {
        _isCustomContentVisible.value = false;
      }
    });
    (0, _defineProperty2.default)(this, "onPrimaryButtonClick", (state, additionalStepData) => {
      const {
        picker,
        indeterminateMap
      } = 'picker' in state ? state : {
        picker: state,
        indeterminateMap: undefined
      };
      const {
        collection
      } = picker;
      const {
        _isModalOpen,
        onSelectRef
      } = this;
      const {
        bulkSelect: {
          selectedValues,
          uncheckedValues,
          allSelected,
          indeterminateSet,
          select
        }
      } = collection;
      _isModalOpen.value = false;
      const selectedCount = allSelected ? collection.result.total - uncheckedValues.length : selectedValues.length;
      onSelectRef.current(selectedValues, {
        uncheckedValues,
        isSelectAll: allSelected,
        selectedCount,
        // backwards compat with pikachu GA
        partiallySelectedIds: indeterminateSet ? Array.from(indeterminateSet) : (indeterminateMap == null ? void 0 : indeterminateMap.partialModeKeys) ?? [],
        values: (select.toArray ?? []).map(({
          value,
          status
        }) => ({
          status,
          value: value.item
        })),
        defaultStatus: select.defaultStatus,
        additionalStepData
      });
    });
    (0, _defineProperty2.default)(this, "openModal", () => {
      const {
        _isOpenButtonClicked,
        _isModalOpen
      } = this;
      _isOpenButtonClicked.value = true;
      _isModalOpen.value = true;
    });
    (0, _defineProperty2.default)(this, "closeModal", () => {
      const {
        _isModalOpen
      } = this;
      _isModalOpen.value = false;
    });
    (0, _defineProperty2.default)(this, "openModalOrCTA", async () => {
      const {
        bi,
        _isOpenButtonClicked,
        fetchFirstPage,
        onSelectRef
      } = this;
      bi.report((0, _bi.pickerPickerOpenButton)({
        action: 'click',
        ...this._commonDynamicBiParams()
      }));
      _isOpenButtonClicked.value = true;
      try {
        await fetchFirstPage.once();
        const {
          status
        } = fetchFirstPage;
        if (status.value.type === 'success' && status.value.data.firstPageResult != null) {
          const {
            firstPageResult: {
              total,
              items
            }
          } = status.value.data;
          if (!this.disableAutoSelectionRef.current && total === 1) {
            bi.report((0, _bi.pickerPickModalCtaButtonClickOrImmediateCta)({
              isImmediate: true,
              itemsCnt: 1,
              listSize: total,
              filteredListSize: total,
              ...this._commonDynamicBiParams()
            }));
            onSelectRef.current(items, {
              uncheckedValues: [],
              isSelectAll: false,
              selectedCount: items.length,
              partiallySelectedIds: [],
              values: [],
              defaultStatus: _bexCore.selectionStatusWixPatternsPreset.checked
            });
            return;
          }
        }
      } catch (e) {
        console.error(e);
      }
      this._isModalOpen.value = true;
    });
    (0, _defineProperty2.default)(this, "getMaxItems", () => {
      const {
        current: multiple
      } = this.multipleRef;
      return typeof multiple === 'number' && Number.isInteger(multiple) ? multiple : multiple ? undefined : 1;
    });
    const {
      onSelect,
      errorMonitor,
      biLoggerFactory,
      environment,
      queryName,
      isOpenInitially = false,
      skipFirstPagePrefetch
    } = params;
    this.minContentHeight = params.minContentHeight ?? 300;
    this.queryName = params.queryName;
    this.fetchData = params.fetchData;
    this.limit = params.limit;
    this._paginationModeRef.current = params.paginationMode;
    this.events = params.events;
    this.filters = params.filters ?? {};
    this.shouldFilterNotAffectTotalCount = params.shouldFilterNotAffectTotalCount ?? (() => false);
    this.environment = environment;
    this.bi = biLoggerFactory().updateDefaults({
      ...(environment.providerType === 'bm' && {
        _hostingPlatform: 'business-manager'
      }),
      artifactId: environment.artifactId,
      componentName: environment.componentName,
      cairoVersion: environment.uiLibVersion,
      ...(0, _bexCore.parseFqdn)(queryName),
      type: 'modal',
      componentType: 'Picker Modal'
    }).logger();
    this._isModalOpen = (0, _bexUtils.reactive)(isOpenInitially);
    this.onSelectRef = {
      current: onSelect
    };
    const onPrefetchPromiseError = err => {
      var _this$events;
      errorMonitor.captureException(err);
      (_this$events = this.events) == null || _this$events.onError == null || _this$events.onError({
        err,
        isOnline: true
      });
    };
    this.fetchFirstPage = new _bexUtils.PromiseState({
      onError: onPrefetchPromiseError,
      fn: async () => {
        const prefetchComputedQuery = ({
          filters: queryFilters
        }) => {
          const hasActiveFilters = (0, _some.default)(queryFilters, filter => (filter == null ? void 0 : filter.initialValue) != null);
          return {
            page: 1,
            limit: params.limit ?? 100,
            offset: 0,
            cursor: null,
            search: undefined,
            rawSearch: '',
            filters: queryFilters,
            rawFilters: queryFilters,
            hasActiveFilters,
            hasNonPersistentActiveFilters: hasActiveFilters
          };
        };
        const firstPagePromise = !skipFirstPagePrefetch ? this.fetchData(prefetchComputedQuery({
          filters: (0, _mapValues.default)(this.filters, filter => filter != null ? filter.initialValue : filter)
        })) : undefined;
        const [firstPageResult] = await Promise.all([firstPagePromise]);
        return {
          firstPageResult
        };
      }
    });
    this.fetchPickerComponent = new _bexUtils.PromiseState({
      onError: onPrefetchPromiseError,
      fn: async () => {
        return (await params.pickerContentComponent()).default;
      }
    });
    this.fetchInitialProps = new _bexUtils.PromiseState({
      onError: onPrefetchPromiseError,
      fn: async () => {
        const [cairoMessages] = await Promise.all([(0, _bexCore.prefetchTranslations)({
          errorMonitor
        })(environment.language).catch(e => {
          console.error(e);
          // Fallback to `PickerModalContent` -> `WixPatternsContainer` i18n init
          return {};
        }), params.fetchInitialProps == null ? void 0 : params.fetchInitialProps()]);
        return {
          cairoMessages
        };
      }
    });
  }
  get isCustomContentVisible() {
    return this._isCustomContentVisible.value;
  }
  get isModalOpen() {
    return this._isModalOpen.value;
  }
  get paginationMode() {
    return this._paginationModeRef.current;
  }
  set paginationMode(value) {
    this._paginationModeRef.current = value;
  }
  get isOpenButtonClicked() {
    return this._isOpenButtonClicked.value;
  }
  get noAvailableItemsFound() {
    var _fetchFirstPage$statu;
    const {
      fetchFirstPage
    } = this;
    return fetchFirstPage.status.value.type === 'success' && ((_fetchFirstPage$statu = fetchFirstPage.status.value.data.firstPageResult) == null ? void 0 : _fetchFirstPage$statu.available) === 0;
  }
  get showButtonLoadingIndication() {
    const {
      _isOpenButtonClicked,
      fetchFirstPage
    } = this;
    return _isOpenButtonClicked.value && fetchFirstPage.status.value.type === 'loading';
  }
  get customContent() {
    return this._customContent.value;
  }
  _commonDynamicBiParams() {
    return {
      maxItems: this.getMaxItems()
    };
  }
  onIsOpenChanged() {
    const {
      isModalOpen
    } = this;
    if (isModalOpen) {
      this.prefetch();
      this._reportModalLoaded();
    }
  }
  init() {
    const {
      bi
    } = this;
    bi.report((0, _bi.pickerPickerOpenButton)({
      action: 'render',
      ...this._commonDynamicBiParams()
    }));

    // if the modal is already open, report startLoad BI, otherwise prefetch dependencies
    if (!this.isModalOpen) {
      // the timeout delay (500) indicates how soon (or late) we want to execute the callback, in case requestIdleCallback is not implemented
      const _requestIdleCallback = window.requestIdleCallback ?? (cb => {
        return window.setTimeout(cb, 500);
      });
      const requestId = _requestIdleCallback(() => {
        this.fetchFirstPage.once();
      });
      return () => {
        if (window.cancelIdleCallback) {
          window.cancelIdleCallback(requestId);
        } else {
          window.clearTimeout(requestId);
        }
      };
    }
    return;
  }
  _reportModalLoaded() {
    this.bi.report((0, _bexCore.withoutDefaults)(_bi.loadStart)({
      ...this._commonDynamicBiParams(),
      url: (0, _bexCore.fixDomainForBI)(window.location.href),
      featuresAvailability: JSON.stringify({})
    }));
  }
}
exports.PickerModalState = PickerModalState;
//# sourceMappingURL=PickerModalState.js.map