"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const react_core_1 = require("@patternfly/react-core");
const utils_1 = require("../hosts/utils");
const AlertsContextProvider_1 = require("../AlertsContextProvider");
const axiosClient_1 = require("../../api/axiosClient");
const utils_2 = require("../../api/utils");
const ClustersAPI_1 = tslib_1.__importDefault(require("../../api/assisted-service/ClustersAPI"));
const use_translation_wrapper_1 = require("../../hooks/use-translation-wrapper");
const utils_3 = require("../../utils");
const getKubeconfigFileName = (headers) => {
    const fileNameMatch = headers['content-disposition'] &&
        headers['content-disposition'].match(/filename=".*"/);
    return fileNameMatch ? fileNameMatch[0].slice(10, -1) : 'kubeconfig';
};
const KubeconfigDownload = ({ clusterId, status, id, handleDownload, className, }) => {
    const { addAlert } = (0, AlertsContextProvider_1.useAlerts)();
    const download = react_1.default.useCallback((clusterId, t) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        try {
            if (axiosClient_1.isInOcm) {
                const { data } = yield ClustersAPI_1.default.getPresignedForClusterCredentials({
                    clusterId,
                    fileName: 'kubeconfig',
                });
                (0, utils_3.downloadFile)(data.url);
            }
            else {
                const response = yield ClustersAPI_1.default.downloadClusterCredentials(clusterId, 'kubeconfig');
                const fileName = getKubeconfigFileName(response.headers);
                (0, utils_3.downloadFile)('', response.data, fileName);
            }
        }
        catch (e) {
            (0, utils_2.handleApiError)(e, (e) => {
                addAlert({
                    title: t('ai:Could not download kubeconfig'),
                    message: (0, utils_2.getApiErrorMessage)(e),
                });
            });
        }
    }), [addAlert]);
    const { t } = (0, use_translation_wrapper_1.useTranslation)();
    return (react_1.default.createElement(react_core_1.Button, { variant: react_core_1.ButtonVariant.secondary, className: className, onClick: handleDownload || (() => download(clusterId, t)), isDisabled: !(0, utils_1.canDownloadKubeconfig)(status), id: id, "data-testid": id }, t('ai:Download kubeconfig')));
};
exports.default = KubeconfigDownload;
//# sourceMappingURL=KubeconfigDownload.js.map