"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.CustomFieldsWidgetState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _bexCore = require("@wix/bex-core");
var _SidePanelsState = require("../SidePanelsState");
var _mobx = require("mobx");
var _bi = require("@wix/bex-core/bi");
var _CustomFieldsPanelState = require("./CustomFieldsPanelState");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
class CustomFieldsWidgetState {
  constructor({
    container,
    fqdn,
    filterable,
    containsPii,
    defaultPermissions,
    extendedFields,
    enableArchive
  }) {
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "dataExtension", void 0);
    (0, _defineProperty2.default)(this, "initTask", new _bexCore.TaskState());
    (0, _defineProperty2.default)(this, "_extendedFields", null);
    (0, _defineProperty2.default)(this, "_formState", null);
    (0, _defineProperty2.default)(this, "_size", void 0);
    (0, _defineProperty2.default)(this, "_widgetContentRef", {
      current: null
    });
    (0, _defineProperty2.default)(this, "panels", void 0);
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "fqdn", void 0);
    (0, _defineProperty2.default)(this, "_customFieldsLazyComponents", undefined);
    (0, _defineProperty2.default)(this, "apps", void 0);
    (0, _defineProperty2.default)(this, "customFieldsPanel", void 0);
    this.container = container;
    this.fqdn = fqdn;
    this._extendedFields = extendedFields;
    this._size = 'default';
    this.panels = new _SidePanelsState.SidePanelsState({
      panelGroupName: (0, _bexCore.fqdnToString)(fqdn),
      container
    });
    this.reportBi = container.createBILogger({
      componentType: 'CustomFieldsWidget',
      ...fqdn
    });
    this.dataExtension = new _bexCore.DataExtensionState({
      container,
      fqdn,
      closeSidePanel: this.panels.closeSidePanel,
      filterable,
      containsPii,
      defaultPermissions,
      enableArchive
    });
    this.apps = new _bexCore.AppsState({
      container,
      dataExtension: this.dataExtension
    });
    this.customFieldsPanel = new _CustomFieldsPanelState.CustomFieldsPanelState({
      dataExtension: this.dataExtension,
      reportBi: this.reportBi,
      closeSidePanel: this.panels.closeSidePanel
    });
    (0, _mobx.makeObservable)(this, {
      hasWritePermissions: _mobx.computed,
      widgetSize: _mobx.computed,
      setWidgetContentRef: _mobx.action,
      isLoading: _mobx.computed,
      isError: _mobx.computed,
      _size: _mobx.observable.ref,
      _widgetContentRef: _mobx.observable.ref,
      _extendedFields: _mobx.observable.ref,
      _adjustWidgetSize: _mobx.action.bound,
      retry: _mobx.action.bound
    });
  }
  get _userFieldsNamespace() {
    return this.dataExtension.dataExtensionService.userFieldsNamespace;
  }
  _appLoadingStart() {
    const startTime = performance.now();
    const commonBiParams = this._commonDynamicBiParams();
    this.reportBi((0, _bi.loadStart)({
      ...commonBiParams
    }));
    return () => {
      this.reportBi((0, _bi.loadEnd)({
        ...commonBiParams,
        loadingTime: Math.round(performance.now() - startTime)
      }));
    };
  }
  init({
    appLoaded
  }) {
    const {
      initTask,
      dataExtension,
      container,
      apps
    } = this;
    const disposers = [dataExtension.init(), apps.init()];
    initTask.runOnce(async () => {
      var _dataExtension$initTa, _container$initTask$s, _apps$initTask$status;
      dataExtension.initTask.runOnce();
      apps.initTask.runOnce();
      const [lazyComponents] = await Promise.all([Promise.resolve().then(() => _interopRequireWildcard(require(/* webpackChunkName: "CustomFieldsWidgetLazyContent" */
      '../../components/CustomFieldsWidget/CustomFieldsWidgetLazyContent'))).catch(err => {
        throw new _bexCore.WixPatternsError({
          errorCode: 'LoadCustomFieldsWidgetLazyContentFailed',
          originalException: err
        });
      }), (_dataExtension$initTa = dataExtension.initTask.status.promise) == null ? void 0 : _dataExtension$initTa.catch(err => {
        throw new _bexCore.WixPatternsError({
          errorCode: 'InitCustomFieldsDataExtensionFailed',
          originalException: err
        });
      }), (_container$initTask$s = container.initTask.status.promise) == null ? void 0 : _container$initTask$s.catch(err => {
        throw new _bexCore.WixPatternsError({
          errorCode: 'InitCustomFieldsWidgetContainerFailed',
          originalException: err
        });
      }), (_apps$initTask$status = apps.initTask.status.promise) == null ? void 0 : _apps$initTask$status.catch(() => null)]).catch(error => {
        this.container.internalMonitor.reportError({
          error
        });
        this.reportBi((0, _bi.cairoErrorInLoadingAComponent)({
          errorType: error instanceof _bexCore.WixPatternsError ? error.name : undefined
        }));
        throw error;
      });
      this._customFieldsLazyComponents = lazyComponents;
      appLoaded == null || appLoaded();
    });
    return () => {
      disposers.forEach(d => d == null ? void 0 : d());
    };
  }
  getNamespaceFormSchemaAndData(namespace) {
    var _extendedFields$names;
    const {
      dataExtension,
      _extendedFields
    } = this;
    const {
      schema,
      fields
    } = dataExtension.getSchemaAndFieldsByNamespace(namespace);
    return {
      fields,
      schema,
      extendedFieldsDataMap: _extendedFields == null || (_extendedFields$names = _extendedFields.namespaces) == null ? void 0 : _extendedFields$names[namespace]
    };
  }
  initContent() {
    const disposers = [(0, _bexCore.addResizeObserver)(this._widgetContentRef.current, this._adjustWidgetSize.bind(this))];
    this._adjustWidgetSize();
    return () => {
      disposers.forEach(d => d == null ? void 0 : d());
    };
  }
  _commonDynamicBiParams() {
    return {
      url: window.location.href,
      route: window.location.pathname
    };
  }
  retry() {
    this.reportBi((0, _bi.cairoTryAgainClicked)({
      actionName: 'Load custom fields',
      loaction: 'Custom fields widget'
    }));
    this.initTask.runOnce();
  }
  get isDirty() {
    var _this$_formState;
    return !!((_this$_formState = this._formState) != null && _this$_formState.isDirty);
  }
  get widgetSize() {
    return this._size;
  }
  get isLoading() {
    const {
      status
    } = this.initTask;
    return status.isIdle || status.isLoading;
  }
  get ActionButtonsComponent() {
    var _this$_customFieldsLa;
    return (_this$_customFieldsLa = this._customFieldsLazyComponents) == null ? void 0 : _this$_customFieldsLa.ActionButtons;
  }
  get CustomFieldsWidgetContent() {
    var _this$_customFieldsLa2;
    return (_this$_customFieldsLa2 = this._customFieldsLazyComponents) == null ? void 0 : _this$_customFieldsLa2.CustomFieldsWidgetContent;
  }
  get WixPatternsModalsContainer() {
    var _this$_customFieldsLa3;
    return (_this$_customFieldsLa3 = this._customFieldsLazyComponents) == null ? void 0 : _this$_customFieldsLa3.WixPatternsModalsContainer;
  }
  get CustomFieldModal() {
    var _this$_customFieldsLa4;
    return (_this$_customFieldsLa4 = this._customFieldsLazyComponents) == null ? void 0 : _this$_customFieldsLa4.CustomFieldModal;
  }
  get ArchiveFieldModal() {
    var _this$_customFieldsLa5;
    return (_this$_customFieldsLa5 = this._customFieldsLazyComponents) == null ? void 0 : _this$_customFieldsLa5.ArchiveFieldModal;
  }
  setWidgetContentRef(ref) {
    this._widgetContentRef.current = ref;
  }
  _adjustWidgetSize() {
    if (this._widgetContentRef.current) {
      const element = this._widgetContentRef.current;
      if (element.clientWidth < 842) {
        this._size = 'small';
      } else {
        this._size = 'default';
      }
    }
  }
  get isError() {
    return this.initTask.status.isError;
  }
  async validate() {
    var _this$_formState2;
    const data = (_this$_formState2 = this._formState) == null ? void 0 : _this$_formState2.validate();
    if (!data) {
      return {
        isValid: true
      };
    }
    if (data != null && data.isValid) {
      const extendedFields = data.extendedFields;
      return {
        isValid: true,
        extendedFields,
        values: extendedFields
      };
    }
    return {
      isValid: false
    };
  }
  get hasWritePermissions() {
    return this.dataExtension.hasWritePermissions;
  }
}
exports.CustomFieldsWidgetState = CustomFieldsWidgetState;
//# sourceMappingURL=CustomFieldsWidgetState.js.map