"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Helper = exports.extractContextKeysFromText = exports.replaceAll = exports.extractColsFromText = exports.clamp = exports.roundNumberTo4dp = exports.roundNumber = exports.isInputNotNullOrEmpty = exports.isInputNullOrEmpty = exports.returnItemCount = exports.copyToClipboard = exports.createDownloadedFile = exports.convertArrayToCsv = exports.arrayToKeyMap = exports.cloneObject = exports.getStringRepresentionFromKey = exports.objectHasKeys = exports.objectNotExists = exports.objectExists = void 0;
const StringExtensions_1 = require("../Extensions/StringExtensions");
const AdaptableLogger_1 = require("../../agGrid/AdaptableLogger");
function objectExists(item) {
    return item != null && item != undefined;
}
exports.objectExists = objectExists;
function objectNotExists(item) {
    return !objectExists(item);
}
exports.objectNotExists = objectNotExists;
function objectHasKeys(item) {
    return Object.keys(item).length > 0;
}
exports.objectHasKeys = objectHasKeys;
function getStringRepresentionFromKey(event) {
    if (event.key == null) {
        return event.char; // IE
    }
    return event.key;
}
exports.getStringRepresentionFromKey = getStringRepresentionFromKey;
function cloneObject(obj) {
    return JSON.parse(JSON.stringify(obj));
}
exports.cloneObject = cloneObject;
const arrayToKeyMap = (arr) => {
    const defaultAccumulator = {};
    if (!arr || !Array.isArray(arr)) {
        return defaultAccumulator;
    }
    return arr.reduce((acc, key) => {
        acc[key] = true;
        return acc;
    }, defaultAccumulator);
};
exports.arrayToKeyMap = arrayToKeyMap;
// converts an array (or an array of arrays) to CSV
function convertArrayToCsv(array, separator = " ' ") {
    let csvContent = '';
    array.forEach((infoArray, index) => {
        let line = [];
        let item;
        let i;
        for (i = 0; i < infoArray.length; ++i) {
            item = infoArray[i];
            if (separator == ',') {
                if (item != null && item != undefined) {
                    if (typeof item === 'string' || item instanceof String) {
                        if (item.indexOf(',') !== -1 || item.indexOf('"') !== -1) {
                            item = `"${item.replace(/"/g, '""')}"`;
                        }
                        // bit of a hack but we have a user where they have "+2502+S" as a value which Excel then thinks is a formula
                        if (item.indexOf('+') == 0) {
                            item = `'${item}'`;
                        }
                    }
                }
            }
            line.push(item);
        }
        csvContent += line.join(separator) + (index != array.length - 1 ? '\n' : '');
    });
    return csvContent;
}
exports.convertArrayToCsv = convertArrayToCsv;
function createDownloadedFile(content, fileName, mimeType) {
    const win = document.defaultView || window;
    if (!win) {
        console.error('No window found, cannot download file');
        return;
    }
    const a = document.createElement('a');
    mimeType = mimeType || 'application/octet-stream';
    if (URL && 'download' in a) {
        // html5 A[download]
        a.href = URL.createObjectURL(new Blob([content], {
            type: mimeType,
        }));
        a.setAttribute('download', fileName);
        document.body.appendChild(a);
        a.dispatchEvent(new MouseEvent('click', {
            bubbles: false,
            cancelable: true,
            view: win,
        }));
        document.body.removeChild(a);
    }
    else {
        location.href = `data:application/octet-stream,${encodeURIComponent(content)}`; // only this mime type is supported
    }
}
exports.createDownloadedFile = createDownloadedFile;
async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        return true;
    }
    catch (ex) {
        AdaptableLogger_1.AdaptableLogger.consoleErrorBase('Copy to clipboard failed.', ex);
        return false;
    }
}
exports.copyToClipboard = copyToClipboard;
function returnItemCount(items, itemName) {
    if (items.length == 0) {
        return `No ${itemName}s`;
    }
    return items.length == 1 ? `1 ${itemName}` : `${items.length} ${itemName}s`;
}
exports.returnItemCount = returnItemCount;
function isInputNullOrEmpty(itemToCheck) {
    if (itemToCheck == 'Invalid Date ') {
        return true;
    }
    if (typeof itemToCheck === 'string') {
        return StringExtensions_1.StringExtensions.IsNullOrEmpty(itemToCheck);
    }
    if (typeof itemToCheck === 'number') {
        return StringExtensions_1.StringExtensions.IsNullOrEmpty(itemToCheck.toString());
    }
    if (itemToCheck instanceof Date) {
        return StringExtensions_1.StringExtensions.IsNullOrEmpty(itemToCheck.toString());
    }
    return itemToCheck == null;
}
exports.isInputNullOrEmpty = isInputNullOrEmpty;
function isInputNotNullOrEmpty(itemToCheck) {
    return !isInputNullOrEmpty(itemToCheck);
}
exports.isInputNotNullOrEmpty = isInputNotNullOrEmpty;
function roundNumber(numberToRound, decimalPlaces) {
    switch (decimalPlaces) {
        case 1:
            return Math.round(numberToRound * 10) / 10;
        case 2:
            return Math.round(numberToRound * 100) / 100;
        case 3:
            return Math.round(numberToRound * 1000) / 1000;
        case 4:
            return Math.round(numberToRound * 10000) / 10000;
        case 5:
            return Math.round(numberToRound * 100000) / 100000;
        case 6:
            return Math.round(numberToRound * 1000000) / 1000000;
    }
}
exports.roundNumber = roundNumber;
function roundNumberTo4dp(numberToRound) {
    return roundNumber(numberToRound, 4);
}
exports.roundNumberTo4dp = roundNumberTo4dp;
// putting this here to remove lodash clamp which seems to cause an issue
function clamp(value, boundOne, boundTwo) {
    if (!boundTwo) {
        return Math.max(value, boundOne) === boundOne ? value : boundOne;
    }
    else if (Math.min(value, boundOne) === value) {
        return boundOne;
    }
    else if (Math.max(value, boundTwo) === value) {
        return boundTwo;
    }
    return value;
}
exports.clamp = clamp;
function extractColsFromText(text) {
    // rowData.columnName => columnName
    const regex = /\[rowData\.(.*?)\]/g;
    let m;
    const cols = [];
    while ((m = regex.exec(text)) !== null) {
        cols.push(m[1]);
    }
    return cols;
}
exports.extractColsFromText = extractColsFromText;
function replaceAll(text, toReplace, replaceWith) {
    if (!text) {
        return text;
    }
    // fails for []
    toReplace = toReplace.replace('[', '\\[').replace(']', '\\]');
    return text.replace(new RegExp(toReplace, 'g'), replaceWith);
}
exports.replaceAll = replaceAll;
function extractContextKeysFromText(text) {
    // context.columnName => columnName
    const regex = /\[context\.(.*?)\]/g;
    let m;
    const contextKeys = [];
    while ((m = regex.exec(text)) !== null) {
        contextKeys.push(m[1]);
    }
    return contextKeys;
}
exports.extractContextKeysFromText = extractContextKeysFromText;
exports.Helper = {
    objectExists,
    objectNotExists,
    objectHasKeys,
    getStringRepresentionFromKey,
    cloneObject,
    convertArrayToCsv,
    createDownloadedFile,
    copyToClipboard,
    returnItemCount,
    isInputNullOrEmpty,
    isInputNotNullOrEmpty,
    roundNumber,
    roundNumberTo4dp,
    clamp,
    extractColsFromText,
    replaceAll,
    extractContextKeysFromText,
};
exports.default = exports.Helper;
