"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const useInfraEnvId_1 = tslib_1.__importDefault(require("./useInfraEnvId"));
const common_1 = require("../../common");
const utils_1 = require("../../common/utils");
const apis_1 = require("../services/apis");
const InfraEnvIdsCacheService_1 = tslib_1.__importDefault(require("../services/InfraEnvIdsCacheService"));
const useInfraEnvHosts = (clusterId, cpuArchitecture, clusterName, pullSecret, openshiftVersion) => {
    const [hosts, setHosts] = react_1.default.useState();
    const [error, setError] = react_1.default.useState('');
    const { infraEnvId, error: infraEnvIdError } = (0, useInfraEnvId_1.default)(clusterId, cpuArchitecture, clusterName, pullSecret, openshiftVersion);
    const getHosts = react_1.default.useCallback(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        try {
            if (infraEnvId) {
                const { data: hostsData } = yield apis_1.InfraEnvsAPI.getHosts(infraEnvId);
                setHosts(hostsData);
            }
        }
        catch (e) {
            // Invalidate this cluster's cached data
            InfraEnvIdsCacheService_1.default.removeInfraEnvId(clusterId, cpuArchitecture);
            setError((0, utils_1.getErrorMessage)(e));
        }
    }), [clusterId, cpuArchitecture, infraEnvId]);
    react_1.default.useEffect(() => {
        if (infraEnvIdError) {
            setHosts(undefined);
            setError(infraEnvIdError);
        }
        else {
            if (infraEnvId) {
                // Initial fetch
                void getHosts();
                // Set up polling to refetch hosts periodically
                const intervalId = setInterval(() => {
                    void getHosts();
                }, common_1.DEFAULT_POLLING_INTERVAL);
                return () => clearInterval(intervalId);
            }
        }
    }, [getHosts, infraEnvId, infraEnvIdError]);
    return { hosts, error, isLoading: !hosts && !error };
};
exports.default = useInfraEnvHosts;
//# sourceMappingURL=useInfraEnvHosts.js.map