"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.CustomFieldModalState = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _mobx = require("mobx");
var _ConditionalModalState = require("./ConditionalModalState");
var _CustomFieldModalBiReporter = require("./CustomFieldModalBiReporter");
var _formstate = require("formstate");
var _ToggleState = require("./ToggleState");
var _util = require("../util");
var _isHttpError = require("../util/isHttpError");
class CustomFieldModalState {
  constructor(params) {
    (0, _defineProperty2.default)(this, "fieldManagement", void 0);
    (0, _defineProperty2.default)(this, "container", void 0);
    (0, _defineProperty2.default)(this, "fieldCount", void 0);
    (0, _defineProperty2.default)(this, "customFieldModalBiReporter", void 0);
    (0, _defineProperty2.default)(this, "settings", new _ToggleState.ToggleState());
    (0, _defineProperty2.default)(this, "errorToastConfig", undefined);
    (0, _defineProperty2.default)(this, "mode", 'new');
    (0, _defineProperty2.default)(this, "origin", 'Custom columns panel');
    (0, _defineProperty2.default)(this, "customOrigin", void 0);
    (0, _defineProperty2.default)(this, "reportBi", void 0);
    (0, _defineProperty2.default)(this, "modalState", new _ConditionalModalState.ConditionalModalState({
      onConfirm: async () => {
        if (this.mode === 'new' && this.fieldManagement.maxReached) {
          return;
        }
        const {
          form,
          mode,
          customFieldModalBiReporter: {
            reportModalEndProcess
          },
          t
        } = this;
        const validation = await form.validate();
        if (validation.hasError) {
          this.enableAutoValidation();
          throw new Error('validation');
        }
        try {
          var _this$container$showT, _this$container;
          const draft = this.getFormValues();
          if (mode === 'new') {
            await this.fieldManagement.addField(draft);
          } else {
            await this.fieldManagement.editField(draft.key, draft);
          }
          (_this$container$showT = (_this$container = this.container).showToast) == null || _this$container$showT.call(_this$container, {
            message: mode === 'new' ? t('cairo.customFields.successToast') : t('cairo.customFields.editCustomField.success.toast'),
            type: 'SUCCESS',
            biName: 'cairo-custom-field-success-toast'
          });
          reportModalEndProcess({
            endType: 'Add Field'
          });
        } catch (e) {
          this.onConfirmError(e);
        }
      }
    }));
    (0, _defineProperty2.default)(this, "form", new _formstate.FormState({
      type: new _formstate.FieldState(undefined).validators(value => {
        if (!value) {
          return this.t('cairo.customFields.addCustomField.modal.emptyFieldType.error');
        }
        return undefined;
      }),
      name: new _formstate.FieldState('').validators(value => {
        if (!value) {
          return this.t('cairo.customFields.addCustomField.modal.emptyFieldName.error');
        }
        return undefined;
      }),
      key: new _formstate.FieldState('').validators(value => {
        const {
          t,
          mode
        } = this;
        if (!value) {
          return this.t('cairo.customFields.addCustomField.modal.emptyFieldName.error');
        }
        if (mode === 'new' && this.containsKey(value)) {
          return t('cairo.customFields.addCustomField.modal.sameKey.error');
        }
        if (!/^[a-zA-Z][a-zA-Z0-9_]*$/g.test(value)) {
          return t('cairo.customFields.addCustomField.modal.keyFormat.error');
        }
        return undefined;
      }),
      readUsers: new _formstate.FieldState(false),
      readApps: new _formstate.FieldState(false),
      writeUsers: new _formstate.FieldState(false),
      writeApps: new _formstate.FieldState(false),
      containsPii: new _formstate.FieldState(false)
    }));
    (0, _defineProperty2.default)(this, "disabledFields", {
      permissions: {
        read: {
          apps: true,
          users: true
        },
        write: {
          apps: true,
          users: true
        }
      }
    });
    (0, _defineProperty2.default)(this, "setKeyFieldIfNotDirty", value => {
      const {
        form: {
          $: {
            key
          }
        },
        mode
      } = this;
      if (mode === 'new' && !key.dirty) {
        // In the formstate library setting a field value using
        // the onChange API sets the dirty state of the field to true.
        // However, since here it's not a manual user input
        // we avoid changing the dirty state by setting a value directly.
        key.value = value;
      }
    });
    this.fieldManagement = params.fieldManagement;
    this.container = params.container;
    this.fieldCount = params.fieldCount;
    this.reportBi = params.reportBi;
    this.customFieldModalBiReporter = new _CustomFieldModalBiReporter.CustomFieldModalBiReporter({
      customFieldModalState: this
    });
    (0, _mobx.makeObservable)(this, {
      namePlaceholder: _mobx.computed,
      isSubmitting: _mobx.computed,
      disabledFields: _mobx.observable.ref,
      errorToastConfig: _mobx.observable.ref,
      mode: _mobx.observable.ref,
      reset: _mobx.action,
      setFormValues: _mobx.action,
      generateUniqueKey: _mobx.action.bound,
      setKeyFieldIfNotDirty: _mobx.action.bound,
      setDefaultPermissions: _mobx.action
    });
  }
  onConfirmError(e) {
    var _this$errorToastConfi;
    const {
      getResolvedError
    } = this.container.errorHandler;
    (0, _mobx.runInAction)(() => {
      var _httpError$response, _httpError$response2, _httpError$response3;
      const resolvedError = getResolvedError == null ? void 0 : getResolvedError(e);
      const httpError = (0, _util.isHttpError)(e) ? e : undefined;
      if ((0, _isHttpError.isDetailsResponse)(httpError == null || (_httpError$response = httpError.response) == null ? void 0 : _httpError$response.data) && (0, _isHttpError.isErrorDetails)(httpError == null || (_httpError$response2 = httpError.response) == null ? void 0 : _httpError$response2.data.details) && httpError != null && (_httpError$response3 = httpError.response) != null && (_httpError$response3 = _httpError$response3.data) != null && (_httpError$response3 = _httpError$response3.details) != null && (_httpError$response3 = _httpError$response3.validationError) != null && (_httpError$response3 = _httpError$response3.fieldViolations) != null && _httpError$response3.some(v => v.ruleName === 'EXCEEDED_STORED_DATA_SIZE')) {
        this.errorToastConfig = {
          message: this.t('cairo.customFields.modal.maxFieldsError'),
          action: {
            text: this.t('cairo.error.contactSupport.cta'),
            onClick: () => {
              window.open('https://www.wix.com/contact', '_blank');
            }
          }
        };
      } else {
        this.errorToastConfig = {
          message: resolvedError == null ? void 0 : resolvedError.message,
          action: resolvedError == null ? void 0 : resolvedError.action,
          details: resolvedError != null && resolvedError.requestId ? {
            requestId: resolvedError.requestId
          } : undefined
        };
      }
    });
    this.customFieldModalBiReporter.reportSubmitFailure({
      errorType: (_this$errorToastConfi = this.errorToastConfig) == null ? void 0 : _this$errorToastConfi.message
    });

    // Prevents modal closing
    throw e;
  }
  reset() {
    const {
      form,
      settings,
      disabledFields: {
        permissions
      }
    } = this;
    form.reset();
    settings.setOff();
    this.errorToastConfig = undefined;
    this.disableAutoValidation();
    permissions.read.apps = false;
    permissions.read.users = false;
    permissions.write.apps = false;
    permissions.write.users = false;
  }
  enableAutoValidation() {
    const {
      form: {
        $: {
          key,
          name,
          type
        }
      }
    } = this;
    key.enableAutoValidation();
    name.enableAutoValidation();
    type.enableAutoValidation();
  }
  disableAutoValidation() {
    const {
      form: {
        $: {
          key,
          name,
          type
        }
      }
    } = this;
    key.disableAutoValidation();
    name.disableAutoValidation();
    type.disableAutoValidation();
  }
  getFormValues() {
    const {
      form: {
        $: {
          type,
          key,
          name,
          readApps,
          readUsers,
          writeApps,
          writeUsers,
          containsPii
        }
      }
    } = this;
    return {
      type: type.value,
      key: key.value,
      name: name.value,
      readApps: readApps.value,
      readUsers: readUsers.value,
      writeApps: writeApps.value,
      writeUsers: writeUsers.value,
      containsPii: containsPii.value
    };
  }
  setFormValues(form, params) {
    const {
      form: {
        $
      }
    } = this;
    $.key.value = form.key;
    $.name.value = form.name;
    $.type.value = form.type;
    $.readApps.value = form.readApps;
    $.readUsers.value = form.readUsers;
    $.writeApps.value = form.writeApps;
    $.writeUsers.value = form.writeUsers;
    $.containsPii.value = form.containsPii;
    if (params != null && params.disablePermissionCheckboxes) {
      if (form.readUsers) {
        this.disabledFields.permissions.read.users = true;
      }
      if (form.readApps) {
        this.disabledFields.permissions.read.apps = true;
      }
      if (form.writeUsers) {
        this.disabledFields.permissions.write.users = true;
      }
      if (form.writeApps) {
        this.disabledFields.permissions.write.apps = true;
      }
    }
  }
  setDefaultPermissions() {
    var _permissions$installe, _permissions$siteVisi;
    const {
      form: {
        $
      }
    } = this;
    const permissions = this.fieldManagement.permissions;
    if (!(permissions != null && (_permissions$installe = permissions.installedApps) != null && _permissions$installe.hide)) {
      var _permissions$installe2, _permissions$installe3;
      $.readApps.value = !!(permissions != null && (_permissions$installe2 = permissions.installedApps) != null && _permissions$installe2.defaultRead);
      $.writeApps.value = !!(permissions != null && (_permissions$installe3 = permissions.installedApps) != null && _permissions$installe3.defaultWrite);
    }
    if (!(permissions != null && (_permissions$siteVisi = permissions.siteVisitors) != null && _permissions$siteVisi.hide)) {
      var _permissions$siteVisi2, _permissions$siteVisi3;
      $.readUsers.value = !!(permissions != null && (_permissions$siteVisi2 = permissions.siteVisitors) != null && _permissions$siteVisi2.defaultRead);
      $.writeUsers.value = !!(permissions != null && (_permissions$siteVisi3 = permissions.siteVisitors) != null && _permissions$siteVisi3.defaultWrite);
    }
  }
  containsKey(key) {
    return this.fieldManagement.existingFieldKeys.includes(key);
  }
  generateUniqueKey(name) {
    const slug = (0, _util.slugify)(name);
    const type = this.form.$.type.value;
    if (slug && slug.length >= 4 && !this.containsKey(slug)) {
      return slug;
    }
    if (!type) {
      return '';
    }
    let index = 1;
    while (this.containsKey(`${type}_${index}`)) {
      index += 1;
    }
    return `${type}_${index}`;
  }
  get t() {
    return this.container.translate;
  }
  get isSubmitting() {
    return this.modalState.modal.confirming.isLoading;
  }
  get namePlaceholder() {
    const selected = this.fieldManagement.creatableFieldTypes.find(option => option.id === this.form.$.type.value);
    return (selected == null ? void 0 : selected.namePlaceholder) ?? this.t('cairo.customFields.addCustomField.modal.fieldName.placeholder');
  }
}
exports.CustomFieldModalState = CustomFieldModalState;
//# sourceMappingURL=CustomFieldModalState.js.map