import { action, computed, makeObservable, observable, runInAction, } from 'mobx';
import { ConditionalModalState } from './ConditionalModalState';
import { CustomFieldModalBiReporter } from './CustomFieldModalBiReporter';
import { FieldState, FormState } from 'formstate';
import { ToggleState } from './ToggleState';
import { isHttpError, slugify } from '../util';
import { isDetailsResponse, isErrorDetails } from '../util/isHttpError';
export class CustomFieldModalState {
    constructor(params) {
        this.settings = new ToggleState();
        this.errorToastConfig = undefined;
        this.mode = 'new';
        this.origin = 'Custom columns panel';
        this.modalState = new 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 {
                    const { dataExtensionSchema } = await dataExtensionState.dataExtensionService.addCustomField({
                        form: this.getFormValues(),
                        schema: this.dataExtensionState.userSchema,
                        fqdn: this.dataExtensionState.fqdnString,
                        filterable: this.dataExtensionState.filterable,
                    });
                    runInAction(() => {
                        if (dataExtensionSchema) {
                            dataExtensionState._upsertSchema(dataExtensionSchema);
                        }
                    });
                    this.dataExtensionState.container.showToast?.({
                        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);
                }
            },
        });
        this.form = new FormState({
            type: new FieldState(undefined).validators((value) => {
                if (!value) {
                    return this.t('cairo.customFields.addCustomField.modal.emptyFieldType.error');
                }
                return undefined;
            }),
            name: new FieldState('').validators((value) => {
                if (!value) {
                    return this.t('cairo.customFields.addCustomField.modal.emptyFieldName.error');
                }
                return undefined;
            }),
            key: new 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 FieldState(false),
            readApps: new FieldState(false),
            writeUsers: new FieldState(false),
            writeApps: new FieldState(false),
            containsPii: new FieldState(false),
        });
        this.disabledFields = {
            permissions: {
                read: { apps: true, users: true },
                write: { apps: true, users: true },
            },
        };
        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({
            customFieldModalState: this,
        });
        makeObservable(this, {
            namePlaceholder: computed,
            isSubmitting: computed,
            disabledFields: observable.ref,
            errorToastConfig: observable.ref,
            mode: observable.ref,
            reset: action,
            setFormValues: action,
            generateUniqueKey: action.bound,
            setKeyFieldIfNotDirty: action.bound,
            setDefaultPermissions: action,
        });
    }
    onConfirmError(e) {
        const { getResolvedError } = this.dataExtensionState.container.errorHandler;
        runInAction(() => {
            const resolvedError = getResolvedError?.(e);
            const httpError = isHttpError(e) ? e : undefined;
            if (isDetailsResponse(httpError?.response?.data) &&
                isErrorDetails(httpError?.response?.data.details) &&
                httpError?.response?.data?.details?.validationError?.fieldViolations?.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?.message,
                    action: resolvedError?.action,
                    details: resolvedError?.requestId
                        ? {
                            requestId: resolvedError.requestId,
                        }
                        : undefined,
                };
            }
        });
        this.customFieldModalBiReporter.reportSubmitFailure({
            errorType: this.errorToastConfig?.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?.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() {
        const { form: { $ }, dataExtensionState: { defaultPermissions }, } = this;
        if (!defaultPermissions?.installedApps?.hide) {
            $.readApps.value = !!defaultPermissions?.installedApps?.defaultRead;
            $.writeApps.value = !!defaultPermissions?.installedApps?.defaultWrite;
        }
        if (!defaultPermissions?.siteVisitors?.hide) {
            $.readUsers.value = !!defaultPermissions?.siteVisitors?.defaultRead;
            $.writeUsers.value = !!defaultPermissions?.siteVisitors?.defaultWrite;
        }
    }
    containsKey(key) {
        return this.dataExtensionState.allUserCustomFields.some((field) => field.id === key);
    }
    generateUniqueKey(name) {
        const slug = 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');
        }
    }
}
//# sourceMappingURL=CustomFieldModalState.js.map