"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClusterDeploymentNetworkingStep = exports.NetworkingForm = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const formik_1 = require("formik");
const react_core_1 = require("@patternfly/react-core");
const common_1 = require("../../../../common");
const ClusterDeploymentNetworkingForm_1 = tslib_1.__importDefault(require("./ClusterDeploymentNetworkingForm"));
const helpers_1 = require("../helpers");
const use_networking_formik_1 = require("../use-networking-formik");
const wizardTransition_1 = require("../wizardTransition");
const use_translation_wrapper_1 = require("../../../../common/hooks/use-translation-wrapper");
const ValidationSection_1 = require("../components/ValidationSection");
const ClusterDeploymentWizardContext_1 = require("../ClusterDeploymentWizardContext");
const NetworkingForm = ({ clusterDeployment, agentClusterInstall, agents, fetchInfraEnv, onEditHost, onEditRole, isPreviewOpen, onSetInstallationDiskId, isNutanix, }) => {
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const { activeStep, goToPrevStep, goToNextStep, close } = (0, react_core_1.useWizardContext)();
    const { syncError } = react_1.default.useContext(ClusterDeploymentWizardContext_1.ClusterDeploymentWizardContext);
    const { alerts } = (0, common_1.useAlerts)();
    const [hasAttemptedSubmit, setHasAttemptedSubmit] = react_1.default.useState(false);
    const [showClusterErrors, setShowClusterErrors] = react_1.default.useState(false);
    const [nextRequested, setNextRequested] = react_1.default.useState(false);
    const { infraEnvWithProxy, infraEnvsError, infraEnvsLoading, sameProxies } = (0, use_networking_formik_1.useInfraEnvProxies)({
        fetchInfraEnv,
        agents,
    });
    const { isValid, isValidating, isSubmitting, validateForm, setTouched, errors, touched, values } = (0, formik_1.useFormikContext)();
    const canContinue = react_1.default.useMemo(() => (0, wizardTransition_1.canNextFromNetworkingStep)(agentClusterInstall, agents), [agentClusterInstall, agents]);
    const onNext = react_1.default.useCallback(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        if (!hasAttemptedSubmit) {
            const errors = yield validateForm();
            setTouched(Object.keys(errors).reduce((acc, curr) => {
                acc[curr] = true;
                return acc;
            }, {}));
            setHasAttemptedSubmit(true);
            if (Object.keys(errors).length) {
                return;
            }
        }
        setNextRequested(true);
    }), [setTouched, hasAttemptedSubmit, validateForm]);
    react_1.default.useEffect(() => {
        setNextRequested(false);
        setShowClusterErrors(false);
    }, [values.apiVips, values.ingressVips]);
    react_1.default.useEffect(() => {
        if (nextRequested) {
            setShowClusterErrors(true);
            if (canContinue) {
                void goToNextStep();
            }
        }
    }, [nextRequested, canContinue, goToNextStep]);
    react_1.default.useEffect(() => {
        if (syncError) {
            setNextRequested(false);
        }
    }, [syncError]);
    const errorFields = (0, common_1.getFormikErrorFields)(errors, touched);
    const submittingText = react_1.default.useMemo(() => {
        if (isSubmitting) {
            return t('ai:Saving changes...');
        }
        else if (isValidating || nextRequested) {
            return t('ai:Validating...');
        }
        return undefined;
    }, [isSubmitting, isValidating, nextRequested, t]);
    const footer = react_1.default.useMemo(() => {
        const hasValidationErrors = hasAttemptedSubmit && (!isValid || isValidating);
        const isNextDisabled = nextRequested || isSubmitting || hasValidationErrors;
        return (react_1.default.createElement(react_core_1.WizardFooter, { activeStep: activeStep, onNext: onNext, isNextDisabled: isNextDisabled, nextButtonProps: { isLoading: !!submittingText }, nextButtonText: submittingText || t('ai:Next'), onBack: goToPrevStep, onClose: close }));
    }, [
        activeStep,
        onNext,
        nextRequested,
        isSubmitting,
        hasAttemptedSubmit,
        isValid,
        isValidating,
        submittingText,
        goToPrevStep,
        close,
        t,
    ]);
    (0, react_core_1.useWizardFooter)(footer);
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(react_core_1.Grid, { hasGutter: true },
            react_1.default.createElement(react_core_1.GridItem, null,
                react_1.default.createElement(common_1.ClusterWizardStepHeader, null, t('ai:Networking'))),
            react_1.default.createElement(react_core_1.GridItem, null,
                react_1.default.createElement(ClusterDeploymentNetworkingForm_1.default, { clusterDeployment: clusterDeployment, agentClusterInstall: agentClusterInstall, agents: agents, sameProxies: sameProxies, infraEnvsError: infraEnvsError, infraEnvWithProxy: infraEnvWithProxy, infraEnvsLoading: infraEnvsLoading, onEditHost: onEditHost, onEditRole: onEditRole, isPreviewOpen: isPreviewOpen, onSetInstallationDiskId: onSetInstallationDiskId, isNutanix: isNutanix })),
            hasAttemptedSubmit && !!errorFields.length && (react_1.default.createElement(react_core_1.GridItem, null,
                react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: t('ai:Provided cluster configuration is not valid'), isInline: true },
                    t('ai:The following fields are invalid or missing'),
                    ":",
                    ' ',
                    errorFields.map((field) => (0, common_1.clusterFieldLabels)(t)[field] || field).join(', '),
                    "."))),
            (showClusterErrors || hasAttemptedSubmit) && !!alerts.length && (react_1.default.createElement(react_core_1.GridItem, null,
                react_1.default.createElement(common_1.Alerts, null))),
            syncError && (react_1.default.createElement(react_core_1.GridItem, null,
                react_1.default.createElement(ValidationSection_1.ValidationSection, { currentStepId: 'networking', hosts: [] },
                    react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: t('ai:An error occurred'), isInline: true }, syncError))))),
        react_1.default.createElement(common_1.FormikAutoSave, null)));
};
exports.NetworkingForm = NetworkingForm;
const ClusterDeploymentNetworkingStep = (_a) => {
    var _b, _c;
    var { clusterDeployment, agentClusterInstall, agents, onSaveNetworking } = _a, rest = tslib_1.__rest(_a, ["clusterDeployment", "agentClusterInstall", "agents", "onSaveNetworking"]);
    const { addAlert } = (0, common_1.useAlerts)();
    const cdName = (_b = clusterDeployment === null || clusterDeployment === void 0 ? void 0 : clusterDeployment.metadata) === null || _b === void 0 ? void 0 : _b.name;
    const cdNamespace = (_c = clusterDeployment === null || clusterDeployment === void 0 ? void 0 : clusterDeployment.metadata) === null || _c === void 0 ? void 0 : _c.namespace;
    const clusterAgents = react_1.default.useMemo(() => agents.filter((a) => (0, helpers_1.isAgentOfCluster)(a, cdName, cdNamespace)), [agents, cdName, cdNamespace]);
    const { initialValues, validationSchema } = (0, use_networking_formik_1.useNetworkingFormik)({
        clusterDeployment,
        agentClusterInstall,
        agents: clusterAgents,
    });
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    const handleSubmit = (values) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        try {
            yield onSaveNetworking(values);
        }
        catch (error) {
            addAlert({
                title: t('ai:Failed to save ClusterDeployment'),
                message: error instanceof Error ? error.message : undefined,
            });
        }
    });
    return (react_1.default.createElement(formik_1.Formik, { initialValues: initialValues, validationSchema: validationSchema, onSubmit: handleSubmit },
        react_1.default.createElement(exports.NetworkingForm, Object.assign({}, rest, { agents: clusterAgents, clusterDeployment: clusterDeployment, agentClusterInstall: agentClusterInstall }))));
};
exports.ClusterDeploymentNetworkingStep = ClusterDeploymentNetworkingStep;
//# sourceMappingURL=ClusterDeploymentNetworkingStep.js.map