"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.PickerStandaloneState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _replaceUrlCurlySegments = require("../utils/replaceUrlCurlySegments");
var _mobx = require("mobx");
var _validateEncodedUrl = require("../utils/validateEncodedUrl");
var _bi = require("@wix/bex-core/bi");
var _matchMediaQuery = require("../utils/matchMediaQuery");
const withoutDefaults = (0, _bexCore.withoutIrrelevant)();
const supportedProtocols = ['https:', 'http:'];
function tryParseUrl(str) {
  try {
    const url = new URL(str);
    (0, _validateEncodedUrl.validateEncodedUrl)(url);
    if (!supportedProtocols.includes(url.protocol)) {
      throw new Error(`Unsupported action url protocol: ${url.protocol}`);
    }
    return url;
  } catch (e) {
    console.error(e);
  }
  return undefined;
}
class PickerStandaloneState {
  constructor(params) {
    var _windowUrl$searchPara;
    (0, _defineProperty2.default)(this, "picker", void 0);
    (0, _defineProperty2.default)(this, "initialSelect", void 0);
    (0, _defineProperty2.default)(this, "noItemsAvailableDestinationUrl", void 0);
    (0, _defineProperty2.default)(this, "defaultDestinationUrl", void 0);
    (0, _defineProperty2.default)(this, "primaryButtonText", void 0);
    (0, _defineProperty2.default)(this, "title", void 0);
    (0, _defineProperty2.default)(this, "subtitle", void 0);
    (0, _defineProperty2.default)(this, "destinationUrlTemplate", void 0);
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "window", void 0);
    (0, _defineProperty2.default)(this, "errorMonitor", void 0);
    (0, _defineProperty2.default)(this, "urlSegmentPropertyMap", void 0);
    (0, _defineProperty2.default)(this, "events", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _bexCore.TaskState());
    (0, _defineProperty2.default)(this, "logoType", void 0);
    (0, _defineProperty2.default)(this, "submitted", false);
    (0, _defineProperty2.default)(this, "isMobileView", void 0);
    (0, _defineProperty2.default)(this, "isDuringSearch", void 0);
    (0, _defineProperty2.default)(this, "_hasCreateNewAction", void 0);
    this.reportBi = params.createBILogger({
      ...params.collection.fqdn,
      type: 'standalone',
      componentType: 'Picker Standalone'
    });
    this.picker = new _bexCore.PickerState({
      getMaxItems: () => 1,
      collection: params.collection,
      shouldFilterNotAffectTotalCount: params.shouldFilterNotAffectTotalCount,
      events: params.events,
      reportBi: this.reportBi,
      loadStartTime: 0 // for standalone we want measure from start of navigation
    });
    this.noItemsAvailableDestinationUrl = params.noItemsAvailableDestinationUrl;
    this.defaultDestinationUrl = params.defaultDestinationUrl;
    this.initialSelect = params.initialSelect;
    this.window = params.window;
    this.errorMonitor = params.errorMonitor;
    this.urlSegmentPropertyMap = params.urlSegmentPropertyMap;
    this.events = params.events ?? {};
    this.logoType = params.logoType;
    const windowUrl = new URL(this.window.location.href);
    this.primaryButtonText = windowUrl.searchParams.get('primaryButtonText');
    this.title = (_windowUrl$searchPara = windowUrl.searchParams.get('title')) == null ? void 0 : _windowUrl$searchPara.trim();
    this.subtitle = windowUrl.searchParams.get('subtitle');
    const maybeActionUrlString = windowUrl.searchParams.get('actionUrl');
    if (maybeActionUrlString) {
      this.destinationUrlTemplate = tryParseUrl(maybeActionUrlString);
    }
    this.isMobileView = !this.window.matchMedia(`(min-width: 768px)`).matches;
    this.isDuringSearch = false;
    (0, _mobx.makeObservable)(this, {
      handlePrimaryButtonClick: _mobx.action.bound,
      submitted: _mobx.observable.ref,
      isMobileView: _mobx.observable.ref,
      isDuringSearch: _mobx.observable.ref,
      setIsDuringSearch: _mobx.action
    });
  }
  onCreateNewClick() {
    this.reportBi(withoutDefaults(_bi.newItemCreationStart)({
      ...this.picker._commonDynamicBiParams()
    }));
  }
  onCreateNewActionCompleted({
    itemId
  }) {
    this.reportBi(withoutDefaults(_bi.newItemCreationEnd)({
      ...this.picker._commonDynamicBiParams(),
      resultType: 'success',
      itemId
    }));
  }
  init() {
    const {
      picker,
      initTask,
      noItemsAvailableDestinationUrl,
      initialSelect,
      window,
      errorMonitor,
      events: {
        onSingleItemAutoNavigation
      }
    } = this;
    const matchMedia = this.window.matchMedia(`(min-width: 768px)`);
    const matchMediaChangeListener = ({
      matches
    }) => {
      this.isMobileView = !matches;
    };
    const disposeMedia = (0, _matchMediaQuery.registerMatchMedia)({
      errorMonitor,
      matchMediaChangeListener,
      matchMedia
    });
    const disposers = [picker.init(), this.subscribeResultUpdated(), disposeMedia];
    initTask.run(async () => {
      await picker.initTask.status.promise;
      await (0, _mobx.runInAction)(async () => {
        const {
          collection
        } = picker;
        const {
          result,
          hasAvailableItems,
          bulkSelect,
          query: {
            search: {
              isEmpty: searchIsEmpty
            }
          }
        } = collection;
        const {
          status,
          keyedItems,
          total
        } = result;
        if (status.isSuccess && !hasAvailableItems && !this._hasCreateNewAction && noItemsAvailableDestinationUrl) {
          window.location.href = noItemsAvailableDestinationUrl;
          await new Promise(() => {}); // keep showing loader while navigating
          return;
        }
        if (status.isSuccess && total === 1 && !this._hasCreateNewAction && searchIsEmpty) {
          const navigated = this.navigateToDestinationUrl(keyedItems[0], onSingleItemAutoNavigation);
          if (navigated) {
            await new Promise(() => {}); // keep showing loader while navigating
          }
          return;
        }
        if (initialSelect) {
          const selectedItem = initialSelect === true ? keyedItems[0] : keyedItems.find(({
            item
          }, index) => initialSelect(item, index));
          if (selectedItem != null) {
            bulkSelect.selectOneItem(selectedItem);
          }
        }
      });
    }, error => {
      errorMonitor.captureException(error);
    });
    return () => {
      for (const disposer of disposers) {
        disposer();
      }
    };
  }
  resolveDestinationUrl(item) {
    const {
      destinationUrlTemplate,
      defaultDestinationUrl,
      urlSegmentPropertyMap
    } = this;
    if (destinationUrlTemplate) {
      return (0, _replaceUrlCurlySegments.replaceUrlCurlySegments)(destinationUrlTemplate, item, urlSegmentPropertyMap);
    }
    if (typeof defaultDestinationUrl === 'string') {
      const url = tryParseUrl(defaultDestinationUrl);
      if (url) {
        return (0, _replaceUrlCurlySegments.replaceUrlCurlySegments)(url, item, urlSegmentPropertyMap);
      }
      return defaultDestinationUrl;
    }
    return defaultDestinationUrl(item);
  }
  navigateToDestinationUrl({
    item,
    index
  }, onNavigate) {
    const {
      window
    } = this;
    const destinationUrl = this.resolveDestinationUrl(item);
    const url = destinationUrl.toString();
    onNavigate == null || onNavigate({
      item,
      index,
      url
    });
    window.location.href = url;
    return true;
  }
  handlePrimaryButtonClick(keyedItem) {
    const {
      events: {
        onContinueToDestinationUrl
      },
      submitted,
      picker,
      reportBi
    } = this;
    if (submitted) {
      return;
    }
    picker.toggle(keyedItem, {
      clear: true
    });
    reportBi((0, _bi.cairoCtaClicked)({
      ...this.picker._commonDynamicBiParams(),
      url: typeof window !== 'undefined' ? window.location.href : '',
      ctaIndex: 1,
      numCtas: 1,
      location: 'pickerStandalone',
      moreActionsIndex: 0,
      ctaName: 'continue'
    }));
    this.submitted = this.navigateToDestinationUrl(keyedItem, onContinueToDestinationUrl);
  }
  setIsDuringSearch(newVal = !this.isDuringSearch) {
    this.isDuringSearch = newVal;
  }
  subscribeResultUpdated() {
    const onResultUpdated = (0, _mobx.action)(() => {
      const {
        picker: {
          collection: {
            result,
            bulkSelect
          }
        }
      } = this;
      bulkSelect.select.filter(value => result.has(value.key));
    });
    const {
      picker: {
        collection
      }
    } = this;
    collection.emitter.on('resultUpdated', onResultUpdated);
    return () => {
      collection.emitter.off('resultUpdated', onResultUpdated);
    };
  }
}
exports.PickerStandaloneState = PickerStandaloneState;
//# sourceMappingURL=PickerStandaloneState.js.map