"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isMajorMinorVersionEqualOrGreater = exports.getComparableVersionInt = exports.getMajorMinorVersion = exports.downloadFile = exports.stringToJSON = exports.validateFileName = exports.getMaxFileSizeMessage = exports.fileSize = exports.validateFileSize = exports.isStringValidJSON = exports.isStringValidYAML = exports.validateFileType = exports.getKeys = exports.getRandomString = exports.getErrorMessage = exports.FILE_TYPE_MESSAGE = exports.FILENAME_REGEX = void 0;
const tslib_1 = require("tslib");
const filesize_js_1 = tslib_1.__importDefault(require("filesize.js"));
const camelCase_js_1 = tslib_1.__importDefault(require("lodash-es/camelCase.js"));
const isString_js_1 = tslib_1.__importDefault(require("lodash-es/isString.js"));
const js_yaml_1 = require("js-yaml");
const configurations_1 = require("./configurations");
exports.FILENAME_REGEX = /^[^\/]*\.(json|ya?ml(\.patch_?[a-zA-Z0-9_]*)?)$/;
exports.FILE_TYPE_MESSAGE = 'Unsupported file type. Please provide a valid YAML file.';
const getErrorMessage = (error) => {
    if (error instanceof Error) {
        return error.message;
    }
    if ((0, isString_js_1.default)(error)) {
        return error;
    }
    return 'Unexpected error';
};
exports.getErrorMessage = getErrorMessage;
const getRandomString = (length) => Array(length + 1)
    .join((Math.random().toString(36) + '00000000000000000').slice(2, 18))
    .slice(0, length);
exports.getRandomString = getRandomString;
const getKeys = (obj) => Object.keys(obj);
exports.getKeys = getKeys;
const validateFileType = (value) => {
    return (0, exports.isStringValidYAML)(value) || (0, exports.isStringValidJSON)(value);
};
exports.validateFileType = validateFileType;
const isStringValidYAML = (input) => {
    try {
        (0, js_yaml_1.loadAll)(input);
        return true;
    }
    catch (_a) {
        return false;
    }
};
exports.isStringValidYAML = isStringValidYAML;
const isStringValidJSON = (input) => {
    try {
        JSON.parse(input);
        return true;
    }
    catch (_a) {
        return false;
    }
};
exports.isStringValidJSON = isStringValidJSON;
const validateFileSize = (value) => {
    const contentFile = new Blob([value], { type: 'text/plain;charset=utf-8' });
    return contentFile.size <= configurations_1.MAX_FILE_SIZE_BYTES * configurations_1.MAX_FILE_SIZE_OFFSET_FACTOR;
};
exports.validateFileSize = validateFileSize;
const fileSize = (...args) => filesize_js_1.default
    .call(null, ...args)
    .toUpperCase()
    .replace(/I/, 'i');
exports.fileSize = fileSize;
const getMaxFileSizeMessage = (t) => t('ai:File size is too big. The file size must be less than {{value}}.', {
    value: (0, exports.fileSize)(configurations_1.MAX_FILE_SIZE_BYTES, 0, 'si'),
});
exports.getMaxFileSizeMessage = getMaxFileSizeMessage;
const validateFileName = (fileName) => {
    return new RegExp(exports.FILENAME_REGEX).test(fileName || '');
};
exports.validateFileName = validateFileName;
const stringToJSON = (jsonString) => {
    let jsObject;
    if (jsonString) {
        try {
            const camelCased = jsonString.replace(/"([\w-]+)":/g, (_match, offset) => `"${(0, camelCase_js_1.default)(offset)}":`);
            jsObject = JSON.parse(camelCased);
        }
        catch (e) {
            // console.error('Failed to parse api string', e, jsonString);
        }
    }
    else {
        // console.info('Empty api string received.');
    }
    return jsObject;
};
exports.stringToJSON = stringToJSON;
const downloadFile = (fileUrl, dataBlob, fileName) => {
    const link = document.createElement('a');
    if (fileUrl && fileUrl !== '') {
        link.setAttribute('href', fileUrl);
    }
    if (dataBlob) {
        const file = new Blob([dataBlob], { type: 'octet/stream' });
        link.setAttribute('href', URL.createObjectURL(file));
    }
    if (fileName) {
        link.setAttribute('download', fileName);
    }
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};
exports.downloadFile = downloadFile;
const getMajorMinorVersion = (version = '') => {
    const match = /[0-9].[0-9][0-9]?/g.exec(version);
    return (match === null || match === void 0 ? void 0 : match[0]) || '';
};
exports.getMajorMinorVersion = getMajorMinorVersion;
// Converts an Openshift version to a comparable integer
const getComparableVersionInt = (version) => {
    const majorMinorParts = version.split('.').slice(0, 2).map(Number);
    if (majorMinorParts.length < 2 || majorMinorParts.some(isNaN)) {
        // If the version doesn't have the required format, returning 0 makes it be considered
        // older than any other version
        return 0;
    }
    const major = majorMinorParts[0];
    const minor = majorMinorParts[1];
    // Assumes minor versions will not go past 999
    return major * 1000 + minor;
};
exports.getComparableVersionInt = getComparableVersionInt;
/**
 * Handles version comparison for major and minor parts only.
 *
 * @param checkVersion the version we want to know about
 * @param toVersion the version we want to test against
 * @returns true if "checkVersion" is equal or greater than "toVersion" (major and minor only)
 */
const isMajorMinorVersionEqualOrGreater = (checkVersion = '', toVersion) => {
    const checkVersionNum = (0, exports.getComparableVersionInt)(checkVersion);
    const toVersionNum = (0, exports.getComparableVersionInt)(toVersion);
    return checkVersionNum >= toVersionNum;
};
exports.isMajorMinorVersionEqualOrGreater = isMajorMinorVersionEqualOrGreater;
//# sourceMappingURL=utils.js.map