"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useInfraEnv;
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"));
function useInfraEnv(clusterId, cpuArchitecture, clusterName, pullSecret, openshiftVersion) {
    const [infraEnv, setInfraEnv] = 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 getInfraEnv = react_1.default.useCallback(() => tslib_1.__awaiter(this, void 0, void 0, function* () {
        try {
            if (infraEnvId) {
                const { data: infraEnv } = yield apis_1.InfraEnvsAPI.get(infraEnvId);
                setInfraEnv(infraEnv);
            }
        }
        catch (e) {
            // Invalidate this cluster's cached data
            InfraEnvIdsCacheService_1.default.removeInfraEnvId(clusterId, common_1.CpuArchitecture.USE_DAY1_ARCHITECTURE);
            setError((0, utils_1.getErrorMessage)(e));
        }
    }), [clusterId, infraEnvId]);
    const updateInfraEnv = react_1.default.useCallback((infraEnvUpdateParams) => tslib_1.__awaiter(this, void 0, void 0, function* () {
        if (!infraEnvId) {
            throw 'updateInfraEnv should not be called before infra env was loaded';
        }
        apis_1.InfraEnvsAPI.abortLastGetRequest();
        const { data } = yield apis_1.InfraEnvsAPI.update(infraEnvId, infraEnvUpdateParams);
        setInfraEnv(data);
        return data;
    }), [infraEnvId]);
    react_1.default.useEffect(() => {
        if (infraEnvIdError) {
            setError(infraEnvIdError);
        }
        else {
            if (!infraEnv) {
                void getInfraEnv();
            }
        }
    }, [getInfraEnv, infraEnv, infraEnvId, infraEnvIdError]);
    return { infraEnv, error, isLoading: !infraEnv && !error, updateInfraEnv };
}
//# sourceMappingURL=useInfraEnv.js.map