"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useInfraEnvId;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const utils_1 = require("../../common/utils");
const services_1 = require("../services");
const use_feature_1 = require("./use-feature");
function useInfraEnvId(clusterId, cpuArchitecture, clusterName, pullSecret, openshiftVersion) {
    const [infraEnvId, setInfraEnv] = react_1.default.useState();
    const [error, setError] = react_1.default.useState('');
    const isSingleClusterFeatureEnabled = (0, use_feature_1.useFeature)('ASSISTED_INSTALLER_SINGLE_CLUSTER_FEATURE');
    const findInfraEnvId = react_1.default.useCallback(() => tslib_1.__awaiter(this, void 0, void 0, function* () {
        try {
            const infraEnvId = yield services_1.InfraEnvsService.getInfraEnvId(clusterId, cpuArchitecture, isSingleClusterFeatureEnabled);
            if (infraEnvId && !(infraEnvId instanceof Error)) {
                setInfraEnv(infraEnvId);
            }
            else {
                //If infraEnv doesn't exist create a new one
                if (pullSecret) {
                    const infraEnv = yield services_1.InfraEnvsService.create({
                        name: services_1.InfraEnvsService.makeInfraEnvName(cpuArchitecture, clusterName),
                        pullSecret,
                        clusterId,
                        openshiftVersion,
                        cpuArchitecture: cpuArchitecture,
                    });
                    setInfraEnv(infraEnv.id);
                }
            }
        }
        catch (e) {
            setError((0, utils_1.getErrorMessage)(e));
        }
    }), [
        clusterId,
        cpuArchitecture,
        isSingleClusterFeatureEnabled,
        pullSecret,
        clusterName,
        openshiftVersion,
    ]);
    react_1.default.useEffect(() => {
        if (!clusterId) {
            setError('Missing clusterId to load infrastructure environment');
        }
        else if (!infraEnvId) {
            void findInfraEnvId();
        }
    }, [clusterId, findInfraEnvId, infraEnvId]);
    return { infraEnvId, error };
}
//# sourceMappingURL=useInfraEnvId.js.map