"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_core_1 = require("@patternfly/react-core");
const formik_1 = require("formik");
const react_1 = tslib_1.__importDefault(require("react"));
const common_1 = require("../../../../common");
const services_1 = require("../../../services");
const ModalDialogsContext_1 = require("../../hosts/ModalDialogsContext");
const api_1 = require("../../../../common/api");
const Day2WizardContext_1 = require("./Day2WizardContext");
const Day2WizardNav_1 = tslib_1.__importDefault(require("./Day2WizardNav"));
const Day2WizardFooter_1 = tslib_1.__importDefault(require("./Day2WizardFooter"));
const Day2StaticIpHostConfigurations_1 = tslib_1.__importDefault(require("./Day2StaticIpHostConfigurations"));
const CpuArchitectureService_1 = require("../../../services/CpuArchitectureService");
const CpuArchitectureDropdown_1 = tslib_1.__importDefault(require("../../clusterConfiguration/CpuArchitectureDropdown"));
const hooks_1 = require("../../../hooks");
const OpenShiftVersionsContext_1 = require("../../clusterWizard/OpenShiftVersionsContext");
const utils_1 = require("../../utils");
const getDay2ClusterDetailInitialValues = (clusterId, day1CpuArchitecture, pullSecret, name, openshiftVersion) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
    try {
        const infraEnv = yield services_1.InfraEnvsService.getInfraEnv(clusterId, day1CpuArchitecture);
        if (infraEnv && !(infraEnv instanceof Error)) {
            return {
                cpuArchitecture: day1CpuArchitecture,
                hostsNetworkConfigurationType: infraEnv.staticNetworkConfig
                    ? services_1.HostsNetworkConfigurationType.STATIC
                    : services_1.HostsNetworkConfigurationType.DHCP,
            };
        }
        else {
            //Create a new InfraEnv because is not found
            if (pullSecret) {
                const infraEnv = yield services_1.InfraEnvsService.create({
                    name: services_1.InfraEnvsService.makeInfraEnvName(day1CpuArchitecture, name),
                    pullSecret,
                    clusterId,
                    openshiftVersion,
                    cpuArchitecture: day1CpuArchitecture,
                });
                return {
                    cpuArchitecture: day1CpuArchitecture,
                    hostsNetworkConfigurationType: infraEnv.staticNetworkConfig
                        ? services_1.HostsNetworkConfigurationType.STATIC
                        : services_1.HostsNetworkConfigurationType.DHCP,
                };
            }
            else {
                return new Error('Could not get infraEnv for this cpu architecture');
            }
        }
    }
    catch (error) {
        (0, api_1.handleApiError)(error);
        return new Error('Could not get infraEnv for this cpu architecture');
    }
});
const Day2ClusterDetails = () => {
    const { day2DiscoveryImageDialog } = (0, ModalDialogsContext_1.useModalDialogsContext)();
    const { close, data: { cluster: day2Cluster }, } = day2DiscoveryImageDialog;
    const wizardContext = (0, Day2WizardContext_1.useDay2WizardContext)();
    const [initialValues, setInitialValues] = react_1.default.useState(null);
    const [isSubmitting, setSubmitting] = react_1.default.useState(false);
    const [isAlternativeCpuSelected, setIsAlternativeCpuSelected] = react_1.default.useState(false);
    const { getCpuArchitectures } = (0, OpenShiftVersionsContext_1.useOpenShiftVersionsContext)();
    const cpuArchitecturesByVersionImage = getCpuArchitectures(day2Cluster.openshiftVersion);
    const day1CpuArchitecture = (0, CpuArchitectureService_1.mapClusterCpuArchToInfraEnvCpuArch)(day2Cluster.cpuArchitecture);
    const [errorState, setErrorState] = react_1.default.useState(null);
    const pullSecret = (0, hooks_1.usePullSecret)();
    const cpuArchitectures = react_1.default.useMemo(() => (0, common_1.getSupportedCpuArchitectures)(cpuArchitecturesByVersionImage, day1CpuArchitecture), [cpuArchitecturesByVersionImage, day1CpuArchitecture]);
    react_1.default.useEffect(() => {
        const fetchAndSetInitialValues = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
            const initialValues = yield getDay2ClusterDetailInitialValues(day2Cluster.id, day1CpuArchitecture, pullSecret, day2Cluster.name, day2Cluster.openshiftVersion);
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            if (initialValues instanceof Error) {
                setErrorState(initialValues);
            }
            else {
                setInitialValues(initialValues);
            }
        });
        void fetchAndSetInitialValues();
    }, [
        day2Cluster.id,
        day1CpuArchitecture,
        pullSecret,
        day2Cluster.name,
        day2Cluster.openshiftVersion,
    ]);
    const handleSubmit = react_1.default.useCallback((values) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        try {
            setSubmitting(true);
            // - If the user selected DHCP, update all infraEnvs to have DHCP too
            // - If the user selected StaticIP, perform no changes yet.
            //  (The changes will be synced to all the infraEnvs when they are submitted on the StaticIP steps)
            const isDhcp = values.hostsNetworkConfigurationType === services_1.HostsNetworkConfigurationType.DHCP;
            if (isDhcp) {
                yield services_1.InfraEnvsService.updateAllInfraEnvsToDhcp(day2Cluster.id);
            }
            wizardContext.setSelectedCpuArchitecture(values.cpuArchitecture);
            wizardContext.onUpdateHostNetworkConfigType(values.hostsNetworkConfigurationType);
        }
        catch (error) {
            (0, api_1.handleApiError)(error);
        }
        finally {
            setSubmitting(false);
        }
    }), [day2Cluster.id, wizardContext]);
    const changeCpuArchitectureDropdownAsync = react_1.default.useCallback((value, initialValues) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        if (pullSecret === undefined) {
            setErrorState(new Error('Pull secret is missing'));
        }
        else {
            if (value !== initialValues.cpuArchitecture) {
                //Fetch infraEnv by clusterId and cpu architecture
                let infraEnv;
                try {
                    infraEnv = yield services_1.InfraEnvsService.getInfraEnv(day2Cluster.id, value);
                    if (!infraEnv || infraEnv instanceof Error) {
                        try {
                            infraEnv = yield services_1.InfraEnvsService.create({
                                name: services_1.InfraEnvsService.makeInfraEnvName(value, day2Cluster.name),
                                pullSecret,
                                clusterId: day2Cluster.id,
                                openshiftVersion: day2Cluster.openshiftVersion,
                                cpuArchitecture: value,
                            });
                        }
                        catch (_a) {
                            setErrorState(new Error('Could not get infraEnv for this cpu architecture'));
                        }
                    }
                }
                catch (_b) {
                    setErrorState(new Error('Could not get infraEnv for this cpu architecture'));
                }
            }
        }
        setIsAlternativeCpuSelected(value !== initialValues.cpuArchitecture);
    }), [day2Cluster.id, day2Cluster.name, day2Cluster.openshiftVersion, pullSecret]);
    const handleChangeCpuArchitectureDropdown = react_1.default.useCallback((value, initialValues) => void changeCpuArchitectureDropdownAsync(value, initialValues), [changeCpuArchitectureDropdownAsync]);
    if (initialValues === null) {
        return react_1.default.createElement(common_1.LoadingState, null);
    }
    else if (errorState !== null) {
        return react_1.default.createElement(common_1.ErrorState, { content: errorState.message });
    }
    return (react_1.default.createElement(formik_1.Formik, { initialValues: initialValues, onSubmit: handleSubmit }, ({ submitForm }) => {
        var _a;
        return (react_1.default.createElement(common_1.ClusterWizardStep, { navigation: react_1.default.createElement(Day2WizardNav_1.default, null), footer: react_1.default.createElement(Day2WizardFooter_1.default, { onNext: () => {
                    void submitForm();
                }, onCancel: close, isSubmitting: isSubmitting }) },
            react_1.default.createElement(formik_1.Form, { id: "day2-wizard-cluster-details__form" },
                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, "Cluster details")),
                    react_1.default.createElement(react_core_1.GridItem, { span: 12, xl: 10 },
                        react_1.default.createElement(CpuArchitectureDropdown_1.default, { openshiftVersion: day2Cluster.openshiftVersion, day1CpuArchitecture: initialValues.cpuArchitecture, cpuArchitectures: cpuArchitectures, onChange: (value) => handleChangeCpuArchitectureDropdown(value, initialValues), platformType: (_a = day2Cluster.platform) === null || _a === void 0 ? void 0 : _a.type })),
                    isAlternativeCpuSelected && (react_1.default.createElement(react_core_1.GridItem, { span: 12, xl: 10 },
                        react_1.default.createElement(react_core_1.Alert, { isInline: true, variant: "info", title: 'To check if the current version of your cluster supports multiple CPU architectures,' },
                            react_1.default.createElement(react_1.default.Fragment, null,
                                react_1.default.createElement(common_1.ExternalLink, { href: common_1.HOW_TO_KNOW_IF_CLUSTER_SUPPORTS_MULTIPLE_CPU_ARCHS }, "follow these steps"))))),
                    react_1.default.createElement(react_core_1.GridItem, null,
                        react_1.default.createElement(Day2StaticIpHostConfigurations_1.default, { isDisabled: (0, utils_1.isOciPlatformType)(day2Cluster) }))))));
    }));
};
exports.default = Day2ClusterDetails;
//# sourceMappingURL=Day2ClusterDetails.js.map