"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useOpenShiftVersionsContext = exports.OpenShiftVersionsContextProvider = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importStar(require("react"));
const api_1 = require("../../../common/api");
const apis_1 = require("../../services/apis");
const utils_1 = require("../../../common/utils");
const supportedVersionLevels = ['production', 'maintenance'];
const OpenShiftVersionsContext = (0, react_1.createContext)(null);
const OpenShiftVersionsContextProvider = ({ children }) => {
    const [allVersions, setAllVersions] = react_1.default.useState([]);
    const [latestVersions, setLatestVersions] = react_1.default.useState([]);
    const [error, setError] = react_1.default.useState();
    const [isLoading, setIsLoading] = react_1.default.useState(true);
    const sortVersions = (versions) => {
        return versions.sort((version1, version2) => version1.value.localeCompare(version2.value, undefined, { numeric: true }));
    };
    react_1.default.useEffect(() => {
        const getVersions = (latest, setVersions) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
            try {
                const { data } = yield apis_1.SupportedOpenshiftVersionsAPI.list(latest);
                const versions = (0, utils_1.getKeys)(data).map((key) => {
                    const versionItem = data[key];
                    const version = versionItem.displayName;
                    return {
                        label: `OpenShift ${version}`,
                        value: key,
                        version,
                        default: Boolean(versionItem.default),
                        supportLevel: versionItem.supportLevel,
                        cpuArchitectures: versionItem.cpuArchitectures,
                    };
                });
                const sorted = sortVersions(versions);
                setVersions(sorted);
                if (!latest && sorted.length === 0) {
                    setError({
                        title: 'Failed to retrieve list of supported OpenShift versions.',
                        message: 'No OpenShift versions available.',
                    });
                }
            }
            catch (e) {
                (0, api_1.handleApiError)(e, (e) => {
                    setError({
                        title: 'Failed to retrieve list of supported OpenShift versions.',
                        message: (0, api_1.getApiErrorMessage)(e),
                    });
                });
            }
        });
        void Promise.allSettled([
            getVersions(false, setAllVersions),
            getVersions(true, setLatestVersions),
        ]).finally(() => setIsLoading(false));
    }, []);
    const findVersionItemByVersion = react_1.default.useCallback((version) => {
        return allVersions === null || allVersions === void 0 ? void 0 : allVersions.find(({ value: versionKey }) => {
            // For version 4.10 match 4.10, 4.10.3, not 4.1, 4.1.5
            const versionNameMatch = new RegExp(`^${versionKey}(\\..+)?$`);
            return versionNameMatch.test(version || '');
        });
    }, [allVersions]);
    const isSupportedOpenShiftVersion = react_1.default.useCallback((version) => {
        if ((allVersions === null || allVersions === void 0 ? void 0 : allVersions.length) === 0) {
            // Till the data are loaded
            return true;
        }
        const selectedVersion = findVersionItemByVersion(version);
        return supportedVersionLevels.includes((selectedVersion === null || selectedVersion === void 0 ? void 0 : selectedVersion.supportLevel) || '');
    }, [findVersionItemByVersion, allVersions]);
    const getCpuArchitectures = react_1.default.useCallback((version) => {
        var _a;
        // TODO (multi-arch) confirm this is correctly retrieving the associated version
        const matchingVersion = findVersionItemByVersion(version);
        return (_a = matchingVersion === null || matchingVersion === void 0 ? void 0 : matchingVersion.cpuArchitectures) !== null && _a !== void 0 ? _a : [];
    }, [findVersionItemByVersion]);
    return (react_1.default.createElement(OpenShiftVersionsContext.Provider, { value: {
            allVersions,
            latestVersions,
            loading: !error && isLoading,
            error,
            isSupportedOpenShiftVersion,
            getCpuArchitectures,
        } }, children));
};
exports.OpenShiftVersionsContextProvider = OpenShiftVersionsContextProvider;
const useOpenShiftVersionsContext = () => {
    const context = react_1.default.useContext(OpenShiftVersionsContext);
    if (!context) {
        throw new Error('useOpenShiftVersionsContext must be used within OpenShiftVersionsContext');
    }
    return context;
};
exports.useOpenShiftVersionsContext = useOpenShiftVersionsContext;
//# sourceMappingURL=OpenShiftVersionsContext.js.map