"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, "dataExtensionState", 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.dataExtensionState.isReachedMaxCustomFields) {
          return;
        }
        const {
          form,
          mode,
          customFieldModalBiReporter: {
            reportModalEndProcess
          },
          t
        } = this;
        const validation = await form.validate();
        if (validation.hasError) {
          this.enableAutoValidation();
          throw new Error('validation');
        }
        const {
          dataExtensionState
        } = this;
        try {
          var _this$dataExtensionSt, _this$dataExtensionSt2;
          const {
            dataExtensionSchema
          } = await dataExtensionState.dataExtensionService.addCustomField({
            form: this.getFormValues(),
            schema: this.dataExtensionState.userSchema,
            fqdn: this.dataExtensionState.fqdnString,
            filterable: this.dataExtensionState.filterable
          });
          (0, _mobx.runInAction)(() => {
            if (dataExtensionSchema) {
              dataExtensionState._upsertSchema(dataExtensionSchema);
            }
          });
          (_this$dataExtensionSt = (_this$dataExtensionSt2 = this.dataExtensionState.container).showToast) == null || _this$dataExtensionSt.call(_this$dataExtensionSt2, {
            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,
          dataExtensionState: {
            allUserCustomFields
          }
        } = this;
        if (!value) {
          return this.t('cairo.customFields.addCustomField.modal.emptyFieldName.error');
        }
        if (mode === 'new' && allUserCustomFields.some(field => field.id === 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.dataExtensionState = params.dataExtensionState;
    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.dataExtensionState.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 _defaultPermissions$i, _defaultPermissions$s;
    const {
      form: {
        $
      },
      dataExtensionState: {
        defaultPermissions
      }
    } = this;
    if (!(defaultPermissions != null && (_defaultPermissions$i = defaultPermissions.installedApps) != null && _defaultPermissions$i.hide)) {
      var _defaultPermissions$i2, _defaultPermissions$i3;
      $.readApps.value = !!(defaultPermissions != null && (_defaultPermissions$i2 = defaultPermissions.installedApps) != null && _defaultPermissions$i2.defaultRead);
      $.writeApps.value = !!(defaultPermissions != null && (_defaultPermissions$i3 = defaultPermissions.installedApps) != null && _defaultPermissions$i3.defaultWrite);
    }
    if (!(defaultPermissions != null && (_defaultPermissions$s = defaultPermissions.siteVisitors) != null && _defaultPermissions$s.hide)) {
      var _defaultPermissions$s2, _defaultPermissions$s3;
      $.readUsers.value = !!(defaultPermissions != null && (_defaultPermissions$s2 = defaultPermissions.siteVisitors) != null && _defaultPermissions$s2.defaultRead);
      $.writeUsers.value = !!(defaultPermissions != null && (_defaultPermissions$s3 = defaultPermissions.siteVisitors) != null && _defaultPermissions$s3.defaultWrite);
    }
  }
  containsKey(key) {
    return this.dataExtensionState.allUserCustomFields.some(field => field.id === 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.dataExtensionState.container.translate;
  }
  get isSubmitting() {
    return this.modalState.modal.confirming.isLoading;
  }
  get namePlaceholder() {
    const {
      t,
      form: {
        $: {
          type
        }
      }
    } = this;
    switch (type.value) {
      case 'dropdown':
        return t('cairo.customFields.fieldType.dropdownList.Name.placeholder');
      case 'checkbox':
        return t('cairo.customFields.fieldType.checkbox.Name.placeholder');
      case 'shortText':
        return t('cairo.customFields.fieldType.shortText.Name.placeholder');
      case 'longText':
        return t('cairo.customFields.fieldType.longText.Name.placeholder');
      case 'url':
        return t('cairo.customFields.placeholder.url');
      case 'date':
        return t('cairo.customFields.fieldType.date.Name.placeholder');
      case 'dateTime':
        return t('cairo.customFields.fieldType.dateAndTime.Name.placeholder');
      case 'integer':
        return t('cairo.customFields.fieldType.numberInteger.Name.placeholder');
      case 'decimal':
        return t('cairo.customFields.fieldType.numberDecimal.Name.placeholder');
      default:
        return t('cairo.customFields.addCustomField.modal.fieldName.placeholder');
    }
  }
}
exports.CustomFieldModalState = CustomFieldModalState;
//# sourceMappingURL=CustomFieldModalState.js.map