"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StaticIpForm = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const react_redux_1 = require("react-redux");
const react_core_1 = require("@patternfly/react-core");
const formik_1 = require("formik");
const isEqual_js_1 = tslib_1.__importDefault(require("lodash-es/isEqual.js"));
const common_1 = require("../../../../../common");
const ErrorMonitorContext_1 = require("../../../../../common/components/ErrorHandling/ErrorMonitorContext");
const api_1 = require("../../../../../common/api");
const selectors_1 = require("../../../../store/slices/current-cluster/selectors");
/** Reports form state and triggers save on every value change (useFormikAutoSave) */
const AutosaveWithParentUpdate = ({ onFormStateChange, getEmptyValues, }) => {
    const emptyValues = react_1.default.useMemo(() => getEmptyValues(), [getEmptyValues]);
    const { isSubmitting, isValid, touched, errors, values, initialValues, submitForm } = (0, formik_1.useFormikContext)();
    const isEmpty = react_1.default.useMemo(() => (0, isEqual_js_1.default)(values, emptyValues), [values, emptyValues]);
    const isAutoSaveRunning = (0, common_1.useFormikAutoSave)(0);
    // Submit once on mount when form was opened with existing data (so it gets persisted).
    react_1.default.useEffect(() => {
        if (!(0, isEqual_js_1.default)(emptyValues, initialValues)) {
            void submitForm();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps -- intentional: run only on mount.
    }, []);
    react_1.default.useEffect(() => {
        onFormStateChange({
            isSubmitting,
            isAutoSaveRunning,
            isValid,
            touched,
            errors,
            isEmpty,
            values: values,
        });
    }, [
        isSubmitting,
        isValid,
        isAutoSaveRunning,
        touched,
        errors,
        values,
        isEmpty,
        onFormStateChange,
    ]);
    return null;
};
const StaticIpForm = ({ infraEnv, updateInfraEnv, getInitialValues, getUpdateParams, validationSchema, onFormStateChange, getEmptyValues, children, showEmptyValues, }) => {
    const { clearAlerts, addAlert } = (0, common_1.useAlerts)();
    const { captureException } = (0, ErrorMonitorContext_1.useErrorMonitor)();
    const { isViewerMode } = (0, react_redux_1.useSelector)(selectors_1.selectCurrentClusterPermissionsState);
    const initialValues = showEmptyValues ? getEmptyValues() : getInitialValues(infraEnv);
    const handleSubmit = (values) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        clearAlerts();
        try {
            yield updateInfraEnv({
                staticNetworkConfig: getUpdateParams(infraEnv, values),
            });
        }
        catch (error) {
            captureException(error);
            addAlert({
                title: 'Failed to update the static network config',
                message: (0, api_1.getApiErrorMessage)(error),
            });
        }
    });
    const validate = (values) => {
        try {
            validationSchema.validateSync(values, {
                abortEarly: false,
                context: { values },
            });
            return {};
        }
        catch (error) {
            return (0, formik_1.yupToFormErrors)(error);
        }
    };
    if (!initialValues) {
        return null;
    }
    const onSubmit = isViewerMode ? () => Promise.resolve() : handleSubmit;
    return (react_1.default.createElement(formik_1.Formik, { initialValues: initialValues, onSubmit: onSubmit, validate: validate, validateOnMount: true },
        react_1.default.createElement(react_core_1.Form, null,
            children,
            react_1.default.createElement(AutosaveWithParentUpdate, { onFormStateChange: onFormStateChange, getEmptyValues: getEmptyValues }))));
};
exports.StaticIpForm = StaticIpForm;
//# sourceMappingURL=StaticIpForm.js.map