"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.areOnlySoftValidationsFailing = exports.getFailingHostValidations = exports.filterByHostname = exports.getHostLabels = exports.getInventory = exports.getHardwareTypeText = exports.getHostname = exports.getEnabledHosts = exports.getTotalHostCount = exports.getEnabledHostCount = exports.getReadyHostCount = exports.canDownloadClusterLogs = exports.canDownloadHostLogs = exports.getHostRole = exports.canHostnameBeChanged = exports.getHostProgressStageNumber = exports.getHostProgress = exports.getHostProgressStages = exports.canOpenConsole = exports.getHostStatus = exports.canInstallHost = exports.canDownloadKubeconfig = exports.canEditDisks = exports.canEditHostname = exports.canEditRole = exports.canEditHost = exports.canReset = exports.canDelete = exports.canDisable = exports.canEnable = void 0;
const tslib_1 = require("tslib");
const fuse_js_1 = tslib_1.__importDefault(require("fuse.js"));
const utils_1 = require("../../utils");
const config_1 = require("../../config");
const constants_1 = require("../constants");
const api_1 = require("../../api");
const canEnable = (clusterStatus, status) => ['pending-for-input', 'insufficient', 'ready', 'adding-hosts'].includes(clusterStatus) &&
    ['disabled', 'disabled-unbound'].includes(status);
exports.canEnable = canEnable;
const canDisable = (clusterStatus, status) => ['pending-for-input', 'insufficient', 'ready', 'adding-hosts'].includes(clusterStatus) &&
    [
        'discovering',
        'discovering-unbound',
        'disconnected',
        'disconnected-unbound',
        'known',
        'known-unbound',
        'insufficient',
        'insufficient-unbound',
        'pending-for-input',
    ].includes(status);
exports.canDisable = canDisable;
const canDelete = (clusterStatus, status) => ['pending-for-input', 'insufficient', 'ready', 'adding-hosts'].includes(clusterStatus) &&
    [
        'discovering',
        'discovering-unbound',
        'known',
        'known-unbound',
        'disconnected',
        'disconnected-unbound',
        'disabled',
        'disabled-unbound',
        'insufficient',
        'insufficient-unbound',
        'resetting',
        'resetting-pending-user-input',
        'resetting-pending-user-action',
        'installing-pending-user-action',
        'pending-for-input',
        'error',
    ].includes(status);
exports.canDelete = canDelete;
const canReset = (clusterStatus, status) => ['adding-hosts'].includes(clusterStatus) &&
    ['error', 'installing-pending-user-action'].includes(status);
exports.canReset = canReset;
const canEditHost = (clusterStatus, status) => ['pending-for-input', 'insufficient', 'ready', 'adding-hosts'].includes(clusterStatus) &&
    [
        'discovering',
        'discovering-unbound',
        'known',
        'known-unbound',
        'disconnected',
        'disconnected-unbound',
        'disabled',
        'disabled-unbound',
        'insufficient',
        'insufficient-unbound',
        'pending-for-input',
    ].includes(status);
exports.canEditHost = canEditHost;
const canEditRole = (clusterStatus, status, isSNO) => (0, exports.canEditHost)(clusterStatus, status) && !isSNO;
exports.canEditRole = canEditRole;
const canEditHostname = (clusterStatus, host) => {
    // First check if the cluster status allows hostname editing
    if (!['insufficient', 'adding-hosts', 'ready', 'pending-for-input'].includes(clusterStatus)) {
        return false;
    }
    // For Day2 hosts, also check the host status
    if (host && host.kind === 'AddToExistingClusterHost') {
        return (0, exports.canHostnameBeChanged)(host.status);
    }
    return true;
};
exports.canEditHostname = canEditHostname;
exports.canEditDisks = exports.canEditHost;
const canDownloadKubeconfig = (clusterStatus) => ['installing', 'finalizing', 'error', 'cancelled', 'installed', 'adding-hosts'].includes(clusterStatus);
exports.canDownloadKubeconfig = canDownloadKubeconfig;
const canInstallHost = (cluster, hostStatus) => cluster.kind === 'AddHostsCluster' && cluster.status === 'adding-hosts' && hostStatus === 'known';
exports.canInstallHost = canInstallHost;
const getHostStatus = (hostStatus, clusterStatus) => {
    if (api_1.isInOcm && hostStatus === 'installed' && clusterStatus !== 'installed') {
        return 'finalizing';
    }
    return hostStatus;
};
exports.getHostStatus = getHostStatus;
const canOpenConsole = (clusterStatus) => {
    return ['finalizing', 'installed'].includes(clusterStatus);
};
exports.canOpenConsole = canOpenConsole;
const getHostProgressStages = (host) => host.progressStages || [];
exports.getHostProgressStages = getHostProgressStages;
const getHostProgress = (host) => {
    var _a;
    return ((_a = host.progress) === null || _a === void 0 ? void 0 : _a.currentStage)
        ? host.progress
        : {
            currentStage: 'Starting installation',
            progressInfo: undefined,
            installationPercentage: undefined,
        };
};
exports.getHostProgress = getHostProgress;
const getHostProgressStageNumber = (host) => {
    const stages = (0, exports.getHostProgressStages)(host);
    const progress = (0, exports.getHostProgress)(host);
    return Math.round((((progress === null || progress === void 0 ? void 0 : progress.installationPercentage) || 0) / 100) * stages.length);
};
exports.getHostProgressStageNumber = getHostProgressStageNumber;
const canHostnameBeChanged = (hostStatus) => [
    'discovering',
    'discovering-unbound',
    'known',
    'known-unbound',
    'disconnected',
    'disconnected-unbound',
    'insufficient',
    'insufficient-unbound',
    'pending-for-input',
].includes(hostStatus);
exports.canHostnameBeChanged = canHostnameBeChanged;
const getHostRole = (host, t, schedulableMasters, clusterKind) => {
    var _a;
    let roleLabel = `${((_a = (0, config_1.hostRoles)(t).find((role) => role.value === host.role)) === null || _a === void 0 ? void 0 : _a.label) || (0, config_1.hostRoles)(t)[0].label}`;
    if (schedulableMasters && host.role === 'master') {
        roleLabel =
            clusterKind === 'AddHostsCluster'
                ? t('ai:Control plane node')
                : t('ai:Control plane node, Worker');
    }
    return `${roleLabel}${host.bootstrap ? ' (bootstrap)' : ''}`;
};
exports.getHostRole = getHostRole;
const canDownloadHostLogs = (host) => !!host.logsCollectedAt && host.logsCollectedAt !== config_1.TIME_ZERO;
exports.canDownloadHostLogs = canDownloadHostLogs;
const canDownloadClusterLogs = (cluster) => cluster.controllerLogsCollectedAt !== config_1.TIME_ZERO ||
    !!(cluster.hosts || []).find((host) => (0, exports.canDownloadHostLogs)(host));
exports.canDownloadClusterLogs = canDownloadClusterLogs;
const getReadyHostCount = (cluster) => cluster.readyHostCount || 0;
exports.getReadyHostCount = getReadyHostCount;
const getEnabledHostCount = (cluster) => cluster.enabledHostCount || 0;
exports.getEnabledHostCount = getEnabledHostCount;
const getTotalHostCount = (cluster) => cluster.totalHostCount || 0;
exports.getTotalHostCount = getTotalHostCount;
const getEnabledHosts = (hosts = []) => hosts.filter((host) => host.status !== 'disabled');
exports.getEnabledHosts = getEnabledHosts;
const getHostname = (host, inventory) => host.requestedHostname || inventory.hostname || '';
exports.getHostname = getHostname;
const getHardwareTypeText = (inventory, t) => {
    let hardwareTypeText = constants_1.DASH;
    const { systemVendor } = inventory;
    if (systemVendor !== undefined) {
        if (systemVendor.virtual) {
            hardwareTypeText = t('ai:Virtual machine');
        }
        else {
            hardwareTypeText = t('ai:Bare metal');
        }
    }
    return hardwareTypeText;
};
exports.getHardwareTypeText = getHardwareTypeText;
const getInventory = (host) => {
    const { inventory: inventoryString = '' } = host;
    return (0, utils_1.stringToJSON)(inventoryString) || {};
};
exports.getInventory = getInventory;
const getHostLabels = (host) => {
    return host.nodeLabels ? JSON.parse(host.nodeLabels) : {};
};
exports.getHostLabels = getHostLabels;
const filterByHostname = (hosts, hostnameFilter) => {
    if (!hostnameFilter) {
        return { hosts, sorted: false };
    }
    const hostsWithHostname = hosts.map((host) => {
        const { inventory: inventoryString = '' } = host;
        const inventory = (0, utils_1.stringToJSON)(inventoryString) || {};
        const hostname = (0, exports.getHostname)(host, inventory);
        return {
            hostname,
            host,
        };
    });
    const fuse = new fuse_js_1.default(hostsWithHostname, {
        includeScore: true,
        ignoreLocation: true,
        threshold: 0.3,
        keys: ['hostname'],
    });
    const filteredHosts = fuse.search(hostnameFilter);
    const sortedHosts = filteredHosts
        .sort((a, b) => (a.score || 0) - (b.score || 0))
        .map(({ item }) => item.host);
    const sorted = filteredHosts.length > 1 &&
        filteredHosts.some((result, index) => index > 0 && (result.score || 0) !== (filteredHosts[0].score || 0));
    return {
        hosts: sortedHosts,
        sorted,
    };
};
exports.filterByHostname = filterByHostname;
const getFailingHostValidations = (validationsInfo) => Object.keys(validationsInfo).reduce((curr, groupStr) => {
    const group = groupStr;
    const failingValidations = validationsInfo[group].filter((validation) => validation.status === 'failure');
    return [...curr, ...failingValidations];
}, []);
exports.getFailingHostValidations = getFailingHostValidations;
const areOnlySoftValidationsFailing = (validationsInfo) => {
    const failingValidationIds = (0, exports.getFailingHostValidations)(validationsInfo).map((validation) => validation.id);
    if (!failingValidationIds.length)
        return false;
    for (const id of failingValidationIds) {
        if (!['ntp-synced', 'container-images-available', 'mtu-valid'].includes(id)) {
            return false;
        }
    }
    return true;
};
exports.areOnlySoftValidationsFailing = areOnlySoftValidationsFailing;
//# sourceMappingURL=utils.js.map