import { CmdbItem } from '../store/cmdbSlice/thunks'
import { CMDB_ITEM_TYPES, TYPES_NAMES_MAP } from '../store/itemTypes'

export const renderValue = (value) => {
    if (value === null || typeof value === 'string') {
        return value;
    }

    if (Array.isArray(value) || typeof value === 'object') {
        return JSON.stringify(value, null, 2);
    }

    return value;
};

export const getFirstEntryValue = (item?: CmdbItem): any => item?.entries?.[0]?.item_value;
export const getFirstEntryName = (item?: CmdbItem): string => item?.entries?.[0]?.item_name || '';
export const getFirstEntryId = (item?: CmdbItem): number | undefined => item?.entries?.[0]?.id;
export const getFirstEntryHostkey = (item?: CmdbItem): string => item?.entries?.[0]?.hostkey || '';
export const getPolicyId = (item?: CmdbItem): string => item?.meta?.policyId  || '';

type TypedItem = { meta?: Record<string, unknown>; type?: string };

// Module input has no stored type of its own
export const resolveItemType = (item?: TypedItem): string =>
    item?.meta?.moduleName ? CMDB_ITEM_TYPES.MODULE_INPUT : item?.type || '';
export const isModuleInput = (item?: TypedItem): boolean => resolveItemType(item) === CMDB_ITEM_TYPES.MODULE_INPUT;
export const getItemTypeName = (item?: TypedItem): string => TYPES_NAMES_MAP[resolveItemType(item)] || '';

export const aceTheme = isDarkMode => isDarkMode ? "tomorrow_night" : "github";

export const isEditAllowed = (permissions : []) => permissions.includes('cmdb.update');
export const isCreateAllowed = (permissions : []) => permissions.includes('cmdb.create');
export const isDeleteAllowed = (permissions : []) => permissions.includes('cmdb.delete');
