"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomManifestsForm = 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 useClusterCustomManifests_1 = tslib_1.__importDefault(require("../../../../hooks/useClusterCustomManifests"));
const services_1 = require("../../../../services");
const CustomManifestsArray_1 = require("./CustomManifestsArray");
const selectors_1 = require("../../../../store/slices/current-cluster/selectors");
const ClusterWizardContext_1 = require("../../../clusterWizard/ClusterWizardContext");
const apis_1 = require("../../../../services/apis");
const fieldName = 'manifests';
const AutosaveWithParentUpdate = ({ onFormStateChange, getEmptyValues, }) => {
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const emptyValues = react_1.default.useMemo(() => getEmptyValues(), []);
    const { isSubmitting, isValid, touched, errors, values } = (0, formik_1.useFormikContext)();
    const isEmpty = react_1.default.useMemo(() => {
        return (0, isEqual_js_1.default)(values, emptyValues);
    }, [values, emptyValues]);
    const isAutoSaveRunning = (0, common_1.useFormikAutoSave)();
    react_1.default.useEffect(() => {
        onFormStateChange({ isSubmitting, isAutoSaveRunning, isValid, touched, errors, isEmpty });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isSubmitting, isValid, isAutoSaveRunning, touched, errors]);
    return null;
};
const CustomManifestsForm = ({ onFormStateChange, getEmptyValues, cluster, getInitialValues, validationSchema, }) => {
    const { isViewerMode } = (0, react_redux_1.useSelector)(selectors_1.selectCurrentClusterPermissionsState);
    const [initialValues, setInitialValues] = react_1.default.useState();
    const { addAlert, clearAlerts } = (0, common_1.useAlerts)();
    const { customManifests, isLoading, error } = (0, useClusterCustomManifests_1.default)(cluster.id || '', true);
    const customManifestsLocalRef = react_1.default.useRef([]);
    const { updateUISettings, uiSettings } = (0, ClusterWizardContext_1.useClusterWizardContext)();
    react_1.default.useEffect(() => {
        if (customManifests && !customManifestsLocalRef.current.length) {
            const initValues = getInitialValues(customManifests);
            setInitialValues(initValues);
            customManifestsLocalRef.current = !!customManifests.length ? initValues.manifests : [];
        }
    }, [customManifests, getInitialValues]);
    const handleSubmit = react_1.default.useCallback((_a, actions_1) => tslib_1.__awaiter(void 0, [_a, actions_1], void 0, function* ({ manifests }, actions) {
        clearAlerts();
        if (manifests.length < customManifestsLocalRef.current.length) {
            // submit was triggered by deleting a manifest
            customManifestsLocalRef.current = manifests;
            return;
        }
        else {
            actions.setSubmitting(true);
            for (let index = 0; index < manifests.length; index++) {
                try {
                    const manifest = manifests[index];
                    if (manifest.created) {
                        // update manifest
                        const oldManifest = customManifestsLocalRef.current[index];
                        yield services_1.ClustersService.updateCustomManifest(oldManifest, manifest, cluster.id);
                        yield updateUISettings({ customManifestsUpdated: true });
                    }
                    else {
                        // add manifest
                        yield apis_1.ClustersAPI.createCustomManifest(cluster.id, services_1.ClustersService.transformFormViewManifest(manifest));
                        manifests[index].created = true;
                        if (!(uiSettings === null || uiSettings === void 0 ? void 0 : uiSettings.customManifestsAdded)) {
                            yield updateUISettings({ customManifestsAdded: true });
                        }
                    }
                }
                catch (error) {
                    const errorArray = new Array(manifests.length).fill(undefined);
                    errorArray.splice(index, 1, { manifestYaml: 'Failed to save changes' });
                    const errors = {
                        manifests: errorArray,
                    };
                    actions.setErrors(errors);
                    // handleApiErrorInForm(manifests, customManifestsLocalRef.current, actions);
                    (0, common_1.handleApiError)(error, () => addAlert({
                        title: 'Failed to update the custom manifests',
                        message: (0, common_1.getApiErrorMessage)(error),
                    }));
                }
            }
            customManifestsLocalRef.current = manifests;
            actions.setSubmitting(false);
        }
    }), [clearAlerts, cluster.id, uiSettings, updateUISettings, addAlert]);
    const onSubmit = isViewerMode ? () => Promise.resolve() : handleSubmit;
    const validate = (values) => {
        try {
            validationSchema.validateSync(values, { abortEarly: false, context: { values } });
            return {};
        }
        catch (error) {
            return (0, formik_1.yupToFormErrors)(error);
        }
    };
    const renderManifests = react_1.default.useCallback((arrayRenderProps) => (react_1.default.createElement(CustomManifestsArray_1.CustomManifestsArray, Object.assign({}, Object.assign({ clusterId: cluster.id }, arrayRenderProps)))), 
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []);
    if (error) {
        return react_1.default.createElement(common_1.ErrorState, null);
    }
    if (isLoading || !initialValues) {
        return react_1.default.createElement(common_1.LoadingState, { content: "Loading custom manifests ..." });
    }
    return (react_1.default.createElement(formik_1.Formik, { initialValues: initialValues, onSubmit: onSubmit, validate: validate, enableReinitialize: true, validateOnMount: true, validateOnChange: true },
        react_1.default.createElement(react_core_1.Form, null,
            react_1.default.createElement(formik_1.FieldArray, { name: fieldName, render: renderManifests }),
            react_1.default.createElement(AutosaveWithParentUpdate, { onFormStateChange: onFormStateChange, getEmptyValues: getEmptyValues }))));
};
exports.CustomManifestsForm = CustomManifestsForm;
//# sourceMappingURL=CustomManifestsForm.js.map