"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HostsClusterDetailTabContent = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const hooks_1 = require("../../../common/hooks");
const common_1 = require("../../../common");
const hooks_2 = require("../../hooks");
const react_core_1 = require("@patternfly/react-core");
const Day2ClusterService_1 = tslib_1.__importStar(require("../../services/Day2ClusterService"));
const api_1 = require("../../../common/api");
const utils_1 = require("../../../common/api/utils");
const AddHosts_1 = require("../AddHosts");
const featureSupportLevels_1 = require("../featureSupportLevels");
const HostsClusterDetailTabContentErrors_1 = require("./HostsClusterDetailTabContentErrors");
const useInfraEnv_1 = tslib_1.__importDefault(require("../../hooks/useInfraEnv"));
const CpuArchitectureService_1 = require("../../services/CpuArchitectureService");
const OpenShiftVersionsContext_1 = require("../clusterWizard/OpenShiftVersionsContext");
const HostsClusterDetailTabContent = ({ cluster: ocmCluster, isVisible, }) => {
    var _a, _b;
    const [error, setError] = react_1.default.useState();
    const [day2Cluster, setDay2Cluster] = (0, hooks_1.useStateSafely)(null);
    const pullSecret = (0, hooks_2.usePullSecret)();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    const ocmClusterMemo = react_1.default.useMemo(() => ocmCluster, []);
    const handleClickTryAgainLink = react_1.default.useCallback(() => {
        setError(undefined);
        setDay2Cluster(null);
    }, [setDay2Cluster]);
    const { infraEnv } = (0, useInfraEnv_1.default)(ocmCluster.id || '', (0, CpuArchitectureService_1.mapOcmArchToCpuArchitecture)(ocmCluster.cpu_architecture) ||
        common_1.CpuArchitecture.USE_DAY1_ARCHITECTURE, ocmCluster.name, pullSecret, ocmCluster.openshift_version);
    react_1.default.useEffect(() => {
        var _a, _b, _c, _d;
        if (!isVisible) {
            // the tab is not visible, stop polling
            setDay2Cluster(null);
            return;
        }
        const day1ClusterHostCount = ((_b = (_a = ocmClusterMemo === null || ocmClusterMemo === void 0 ? void 0 : ocmClusterMemo.metrics) === null || _a === void 0 ? void 0 : _a.nodes) === null || _b === void 0 ? void 0 : _b.total) || 0;
        const openshiftClusterId = Day2ClusterService_1.default.getOpenshiftClusterId(ocmClusterMemo);
        if (day1ClusterHostCount === 0 || !openshiftClusterId) {
            setError(react_1.default.createElement(HostsClusterDetailTabContentErrors_1.UnableToAddHostsError, { onTryAgain: handleClickTryAgainLink }));
        }
        if (!day2Cluster && pullSecret) {
            const { apiVipDnsname, errorType } = (0, Day2ClusterService_1.getApiVipDnsName)(ocmClusterMemo);
            if (errorType) {
                const wrongUrlMessage = errorType === 'console'
                    ? `Cluster Console URL is not valid (${((_c = ocmClusterMemo.console) === null || _c === void 0 ? void 0 : _c.url) || ''})`
                    : `Cluster API URL is not valid (${((_d = ocmClusterMemo.api) === null || _d === void 0 ? void 0 : _d.url) || ''})`;
                setError(react_1.default.createElement(react_1.default.Fragment, null,
                    wrongUrlMessage,
                    ", you can",
                    ' ',
                    react_1.default.createElement(react_core_1.Button, { variant: 'link', isInline: true, onClick: handleClickTryAgainLink }, "try again"),
                    "."));
                return;
            }
            if (!apiVipDnsname) {
                setError(react_1.default.createElement(react_1.default.Fragment, null, "Neither API nor Console URL has been reported by the cluster yet."));
                return;
            }
            const loadDay2Cluster = () => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
                var _a, _b;
                try {
                    const day2Cluster = yield Day2ClusterService_1.default.fetchCluster(ocmClusterMemo, pullSecret);
                    const aiCluster = Day2ClusterService_1.default.completeAiClusterWithOcmCluster(day2Cluster, ocmClusterMemo);
                    setDay2Cluster(aiCluster !== null && aiCluster !== void 0 ? aiCluster : null);
                }
                catch (e) {
                    (0, api_1.handleApiError)(e);
                    if ((0, utils_1.isApiError)(e)) {
                        const isImport = (_b = (_a = e.config) === null || _a === void 0 ? void 0 : _a.url) === null || _b === void 0 ? void 0 : _b.includes('/import');
                        setError(react_1.default.createElement(HostsClusterDetailTabContentErrors_1.AddHostsApiError, { isImport: isImport || false, onTryAgain: handleClickTryAgainLink }));
                    }
                }
            });
            void loadDay2Cluster();
        }
    }, [pullSecret, day2Cluster, setDay2Cluster, isVisible, handleClickTryAgainLink, ocmClusterMemo]);
    const refreshCluster = react_1.default.useCallback(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        if (!(day2Cluster === null || day2Cluster === void 0 ? void 0 : day2Cluster.id)) {
            return;
        }
        try {
            const updatedDay2Cluster = yield Day2ClusterService_1.default.fetchClusterById(day2Cluster.id);
            const aiCluster = Day2ClusterService_1.default.completeAiClusterWithOcmCluster(updatedDay2Cluster, ocmCluster);
            setDay2Cluster(aiCluster !== null && aiCluster !== void 0 ? aiCluster : null);
        }
        catch (e) {
            (0, api_1.handleApiError)(e);
            setError(react_1.default.createElement(HostsClusterDetailTabContentErrors_1.ReloadFailedError, { onTryAgain: handleClickTryAgainLink }));
        }
    }), [day2Cluster === null || day2Cluster === void 0 ? void 0 : day2Cluster.id, handleClickTryAgainLink, ocmCluster, setDay2Cluster]);
    react_1.default.useEffect(() => {
        const id = setInterval(() => {
            void refreshCluster();
        }, common_1.DEFAULT_POLLING_INTERVAL);
        return () => clearInterval(id);
    }, [refreshCluster]);
    if (error) {
        return (react_1.default.createElement(common_1.ErrorState, { variant: react_core_1.EmptyStateVariant.lg, content: error, title: "Failed to prepare the cluster for adding hosts." }));
    }
    if (!day2Cluster) {
        return react_1.default.createElement(common_1.LoadingState, { content: "Preparing cluster for adding hosts..." });
    }
    return (react_1.default.createElement(common_1.AddHostsContextProvider, { cluster: day2Cluster, resetCluster: refreshCluster, ocpConsoleUrl: (_a = ocmCluster === null || ocmCluster === void 0 ? void 0 : ocmCluster.console) === null || _a === void 0 ? void 0 : _a.url, canEdit: ocmCluster.canEdit },
        react_1.default.createElement(OpenShiftVersionsContext_1.OpenShiftVersionsContextProvider, null,
            react_1.default.createElement(featureSupportLevels_1.NewFeatureSupportLevelProvider, { loadingUi: react_1.default.createElement(common_1.LoadingState, null), cluster: day2Cluster, cpuArchitecture: infraEnv === null || infraEnv === void 0 ? void 0 : infraEnv.cpuArchitecture, openshiftVersion: day2Cluster.openshiftVersion, platformType: (_b = day2Cluster.platform) === null || _b === void 0 ? void 0 : _b.type },
                react_1.default.createElement(AddHosts_1.AddHosts, null)))));
};
exports.HostsClusterDetailTabContent = HostsClusterDetailTabContent;
//# sourceMappingURL=HostsClusterDetailTabContent.js.map