"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const react_router_dom_v5_compat_1 = require("react-router-dom-v5-compat");
const react_redux_1 = require("react-redux");
const common_1 = require("../../../common");
const hooks_1 = require("../../hooks");
const api_1 = require("../../../common/api");
const slice_1 = require("../../store/slices/current-cluster/slice");
const ClusterWizardContext_1 = require("./ClusterWizardContext");
const wizardTransition_1 = require("./wizardTransition");
const hooks_2 = require("../../hooks");
const OpenShiftVersionsContext_1 = require("./OpenShiftVersionsContext");
const ClusterDetailsForm_1 = tslib_1.__importDefault(require("./ClusterDetailsForm"));
const ClusterWizardNavigation_1 = tslib_1.__importDefault(require("./ClusterWizardNavigation"));
const services_1 = require("../../services");
const BundleService_1 = tslib_1.__importDefault(require("../../services/BundleService"));
const use_feature_1 = require("../../hooks/use-feature");
const ClusterDetails = ({ cluster, infraEnv }) => {
    const clusterWizardContext = (0, ClusterWizardContext_1.useClusterWizardContext)();
    const managedDomains = (0, hooks_2.useManagedDomains)();
    const { addAlert, clearAlerts } = (0, common_1.useAlerts)();
    const navigate = (0, react_router_dom_v5_compat_1.useNavigate)();
    const dispatch = (0, react_redux_1.useDispatch)();
    const { usedClusterNames } = (0, hooks_2.useUsedClusterNames)((cluster === null || cluster === void 0 ? void 0 : cluster.id) || '');
    const { error: errorOCPVersions, loading: loadingOCPVersions, latestVersions: versions, } = (0, OpenShiftVersionsContext_1.useOpenShiftVersionsContext)();
    const location = (0, react_router_dom_v5_compat_1.useLocation)();
    const isSingleClusterFeatureEnabled = (0, use_feature_1.useFeature)('ASSISTED_INSTALLER_SINGLE_CLUSTER_FEATURE');
    const fetchedPullSecret = (0, hooks_1.usePullSecret)(isSingleClusterFeatureEnabled);
    /** With a cluster resource, never pre-fill the form with a pull secret (API does not return it); new-cluster flow uses the hook default. */
    const pullSecretForForm = cluster ? '' : fetchedPullSecret !== null && fetchedPullSecret !== void 0 ? fetchedPullSecret : '';
    const handleClusterUpdate = react_1.default.useCallback((clusterId, params) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        clearAlerts();
        try {
            const { data: updatedCluster } = yield services_1.ClustersService.update(clusterId, cluster === null || cluster === void 0 ? void 0 : cluster.tags, params);
            dispatch((0, slice_1.updateCluster)(updatedCluster));
            (0, wizardTransition_1.canNextClusterDetails)({ cluster: updatedCluster }) && clusterWizardContext.moveNext();
        }
        catch (e) {
            (0, api_1.handleApiError)(e, () => addAlert({ title: 'Failed to update the cluster', message: (0, api_1.getApiErrorMessage)(e) }));
            if ((0, api_1.isUnknownServerError)(e)) {
                dispatch((0, slice_1.setServerUpdateError)());
            }
        }
    }), [clearAlerts, addAlert, dispatch, cluster === null || cluster === void 0 ? void 0 : cluster.tags, clusterWizardContext]);
    const handleClusterCreate = react_1.default.useCallback((params) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        var _a;
        clearAlerts();
        try {
            const searchParams = new URLSearchParams(location.search);
            const isAssistedMigration = searchParams.get('source') === 'assisted_migration';
            //For Assisted Migration we need the LVMs operator and also the virtualization bundle operators
            if (isAssistedMigration) {
                params.olmOperators = [{ name: 'lvm' }];
                const selectedBundle = (yield BundleService_1.default.listBundles(params.openshiftVersion, params.cpuArchitecture, (_a = params.platform) === null || _a === void 0 ? void 0 : _a.type)).find((b) => b.id === 'virtualization');
                const virtOperators = selectedBundle === null || selectedBundle === void 0 ? void 0 : selectedBundle.operators;
                params.olmOperators = [
                    ...params.olmOperators,
                    ...(virtOperators ? virtOperators.map((op) => ({ name: op })) : []),
                ];
            }
            const cluster = yield services_1.ClustersService.create(params, isAssistedMigration, isSingleClusterFeatureEnabled);
            navigate(`../${cluster.id}`, { state: wizardTransition_1.ClusterWizardFlowStateNew });
            if (isAssistedMigration) {
                try {
                    const uiPatch = {
                        bundlesSelected: ['virtualization'],
                        isAssistedMigration: true,
                    };
                    yield services_1.UISettingService.update(cluster.id, uiPatch);
                    yield clusterWizardContext.updateUISettings(uiPatch);
                }
                catch (uiError) {
                    (0, api_1.handleApiError)(uiError, () => addAlert({
                        title: 'Failed to update UI settings',
                        message: (0, api_1.getApiErrorMessage)(uiError),
                    }));
                }
            }
        }
        catch (e) {
            (0, api_1.handleApiError)(e, () => addAlert({ title: 'Failed to create new cluster', message: (0, api_1.getApiErrorMessage)(e) }));
            if ((0, api_1.isUnknownServerError)(e)) {
                dispatch((0, slice_1.setServerUpdateError)());
            }
        }
    }), [
        clearAlerts,
        location.search,
        isSingleClusterFeatureEnabled,
        navigate,
        clusterWizardContext,
        addAlert,
        dispatch,
    ]);
    const navigation = react_1.default.createElement(ClusterWizardNavigation_1.default, { cluster: cluster });
    if ((!cluster && fetchedPullSecret === undefined) ||
        !managedDomains ||
        loadingOCPVersions ||
        !usedClusterNames) {
        return (react_1.default.createElement(common_1.ClusterWizardStep, { navigation: navigation },
            react_1.default.createElement(common_1.LoadingState, null)));
    }
    if (!cluster && errorOCPVersions) {
        return (react_1.default.createElement(common_1.ClusterWizardStep, { navigation: navigation },
            react_1.default.createElement(common_1.ErrorState, { title: errorOCPVersions.title || 'Failed to retrieve OpenShift versions', content: errorOCPVersions.message || 'No OpenShift versions available.' })));
    }
    return (react_1.default.createElement(ClusterDetailsForm_1.default, { cluster: cluster, pullSecret: pullSecretForForm, managedDomains: managedDomains, ocpVersions: versions, usedClusterNames: usedClusterNames, handleClusterUpdate: handleClusterUpdate, handleClusterCreate: handleClusterCreate, navigation: navigation, infraEnv: infraEnv }));
};
exports.default = ClusterDetails;
//# sourceMappingURL=ClusterDetails.js.map