"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CancelledException = void 0;
exports.cancellablePromise = cancellablePromise;
exports.castObservableToPromise = castObservableToPromise;
exports.addTreeLevelByMutation = addTreeLevelByMutation;
exports.addTreeLevelAndAggregatorsByMutation = addTreeLevelAndAggregatorsByMutation;
exports.flattenToParentChildArray = flattenToParentChildArray;
exports.getTreeDataOptionPropName = getTreeDataOptionPropName;
exports.unflattenParentChildArrayToTree = unflattenParentChildArrayToTree;
exports.findItemInTreeStructure = findItemInTreeStructure;
exports.decimalFormatted = decimalFormatted;
exports.formatNumber = formatNumber;
exports.getCellValueFromQueryFieldGetter = getCellValueFromQueryFieldGetter;
exports.getDescendantProperty = getDescendantProperty;
exports.getTranslationPrefix = getTranslationPrefix;
exports.getColumnFieldType = getColumnFieldType;
exports.isColumnDateType = isColumnDateType;
exports.mapOperatorType = mapOperatorType;
exports.mapOperatorToShorthandDesignation = mapOperatorToShorthandDesignation;
exports.mapOperatorByFieldType = mapOperatorByFieldType;
exports.objectWithoutKey = objectWithoutKey;
exports.thousandSeparatorFormatted = thousandSeparatorFormatted;
exports.findOrDefault = findOrDefault;
exports.unsubscribeAll = unsubscribeAll;
const un_flatten_tree_1 = require("un-flatten-tree");
const constants_js_1 = require("../constants.js");
const index_js_1 = require("../enums/index.js");
/** Cancelled Extension that can be only be thrown by the `cancellablePromise()` function */
class CancelledException extends Error {
    constructor(message) {
        super(message);
        Object.setPrototypeOf(this, CancelledException.prototype);
    }
}
exports.CancelledException = CancelledException;
/**
 * From an input Promise, make it cancellable by wrapping it inside an object that holds the promise and a `cancel()` method
 * @param {Promise<any>} - input Promise
 * @returns {Object} - Promise wrapper that holds the promise and a `cancel()` method
 */
function cancellablePromise(inputPromise) {
    let hasCancelled = false;
    if (inputPromise instanceof Promise) {
        return {
            promise: inputPromise.then((result) => {
                if (hasCancelled) {
                    throw new CancelledException('Cancelled Promise');
                }
                return result;
            }),
            cancel: () => (hasCancelled = true),
        };
    }
    return inputPromise;
}
/**
 * Try casting an input of type Promise | Observable into a Promise type.
 * @param object which could be of type Promise or Observable
 * @param fromServiceName string representing the caller service name and will be used if we throw a casting problem error
 */
function castObservableToPromise(rxjs, input, fromServiceName = '') {
    let promise = input;
    if (input instanceof Promise) {
        // if it's already a Promise then return it
        return input;
    }
    else if (rxjs.isObservable(input)) {
        promise = rxjs.firstValueFrom(input);
    }
    if (!(promise instanceof Promise)) {
        throw new Error(`Something went wrong, Slickgrid-Universal ${fromServiceName} is not able to convert the Observable into a Promise.`);
    }
    return promise;
}
/**
 * Mutate the original array and add a treeLevel (defaults to `__treeLevel`) property on each item.
 * @param {Array<Object>} treeArray - hierarchical tree array
 * @param {Object} options - options containing info like children & treeLevel property names
 * @param {Number} [treeLevel] - current tree level
 */
function addTreeLevelByMutation(treeArray, options, treeLevel = 0) {
    const childrenPropName = getTreeDataOptionPropName(options, 'childrenPropName');
    if (Array.isArray(treeArray)) {
        treeArray.forEach((item) => {
            if (item) {
                if (Array.isArray(item[childrenPropName]) && item[childrenPropName].length > 0) {
                    treeLevel++;
                    addTreeLevelByMutation(item[childrenPropName], options, treeLevel);
                    treeLevel--;
                }
                item[options.levelPropName] = treeLevel;
            }
        });
    }
}
function addTreeLevelAndAggregatorsByMutation(treeArray, options, treeLevel = 0, parent = null) {
    const childrenPropName = getTreeDataOptionPropName(options, 'childrenPropName');
    const { aggregator } = options;
    if (Array.isArray(treeArray)) {
        treeArray.forEach((item) => {
            if (item) {
                const isParent = Array.isArray(item[childrenPropName]);
                if (Array.isArray(item[childrenPropName]) && item[childrenPropName].length > 0) {
                    aggregator.init(item, true);
                    treeLevel++;
                    addTreeLevelAndAggregatorsByMutation(item[childrenPropName], options, treeLevel, item);
                    treeLevel--;
                }
                if (parent && aggregator.isInitialized && typeof aggregator.accumulate === 'function' && !item?.__filteredOut) {
                    aggregator.accumulate(item, isParent);
                    aggregator.storeResult(parent.__treeTotals);
                }
                item[options.levelPropName] = treeLevel;
            }
        });
    }
}
/**
 * Convert a hierarchical (tree) array (with children) into a flat array structure array (where the children are pushed as next indexed item in the array)
 * Note: for perf reasons, it mutates the array by adding extra props like `treeLevel`
 * @param {Array<Object>} treeArray - input hierarchical (tree) array
 * @param {Object} options - you can provide "childrenPropName" and other options (defaults to "children")
 * @return {Array<Object>} output - Parent/Child array
 */
function flattenToParentChildArray(treeArray, options) {
    const identifierPropName = getTreeDataOptionPropName(options, 'identifierPropName');
    const childrenPropName = getTreeDataOptionPropName(options, 'childrenPropName');
    const hasChildrenPropName = getTreeDataOptionPropName(options, 'hasChildrenPropName');
    const parentPropName = getTreeDataOptionPropName(options, 'parentPropName');
    const levelPropName = getTreeDataOptionPropName(options, 'levelPropName');
    if (options?.shouldAddTreeLevelNumber) {
        if (Array.isArray(options?.aggregators)) {
            options.aggregators.forEach((aggregator) => {
                addTreeLevelAndAggregatorsByMutation(treeArray, { childrenPropName, levelPropName, aggregator });
            });
        }
        else {
            addTreeLevelByMutation(treeArray, { childrenPropName, levelPropName });
        }
    }
    const flat = (0, un_flatten_tree_1.flatten)(treeArray, (node) => node[childrenPropName], (node, parentNode) => {
        return {
            [identifierPropName]: node[identifierPropName],
            [parentPropName]: parentNode !== undefined ? parentNode[identifierPropName] : null,
            [hasChildrenPropName]: !!node[childrenPropName],
            ...objectWithoutKey(node, childrenPropName), // reuse the entire object except the children array property
        };
    });
    return flat;
}
/** Find the associated property name from the Tree Data option when found or return a default property name that we defined internally */
function getTreeDataOptionPropName(treeDataOptions, optionName, defaultDataIdPropName = 'id') {
    let propName = '';
    switch (optionName) {
        case 'childrenPropName':
            propName = treeDataOptions?.childrenPropName ?? constants_js_1.Constants.treeDataProperties.CHILDREN_PROP;
            break;
        case 'collapsedPropName':
            propName = treeDataOptions?.collapsedPropName ?? constants_js_1.Constants.treeDataProperties.COLLAPSED_PROP;
            break;
        case 'hasChildrenPropName':
            propName = treeDataOptions?.hasChildrenPropName ?? constants_js_1.Constants.treeDataProperties.HAS_CHILDREN_PROP;
            break;
        case 'identifierPropName':
            propName = treeDataOptions?.identifierPropName ?? defaultDataIdPropName;
            break;
        case 'levelPropName':
            propName = treeDataOptions?.levelPropName ?? constants_js_1.Constants.treeDataProperties.TREE_LEVEL_PROP;
            break;
        case 'parentPropName':
            propName = treeDataOptions?.parentPropName ?? constants_js_1.Constants.treeDataProperties.PARENT_PROP;
            break;
    }
    return propName;
}
/**
 * Convert a flat array (with "parentId" references) into a hierarchical (tree) dataset structure (where children are array(s) inside their parent objects)
 * Note: for perf reasons, it mutates the array by adding extra props like `treeLevel`
 * @param flatArray input array (flat dataset)
 * @param options you can provide the following tree data options (which are all prop names, except 1 boolean flag, to use or else use their defaults):: collapsedPropName, childrenPropName, parentPropName, identifierPropName and levelPropName and initiallyCollapsed (boolean)
 * @return roots - hierarchical (tree) data view array
 */
function unflattenParentChildArrayToTree(flatArray, options) {
    const identifierPropName = getTreeDataOptionPropName(options, 'identifierPropName');
    const childrenPropName = getTreeDataOptionPropName(options, 'childrenPropName');
    const parentPropName = getTreeDataOptionPropName(options, 'parentPropName');
    const levelPropName = getTreeDataOptionPropName(options, 'levelPropName');
    const collapsedPropName = getTreeDataOptionPropName(options, 'collapsedPropName');
    const inputArray = flatArray || [];
    const roots = []; // items without parent which at the root
    // make them accessible by guid on this map
    const all = {};
    inputArray.forEach((item) => {
        all[item[identifierPropName]] = item;
        delete item[childrenPropName];
    });
    // connect childrens to its parent, and split roots apart
    Object.keys(all).forEach((id) => {
        const item = all[id];
        if (!(parentPropName in item) || item[parentPropName] === null || item[parentPropName] === undefined || item[parentPropName] === '') {
            roots.push(item);
        }
        else if (item[parentPropName] in all) {
            const p = all[item[parentPropName]];
            if (!(childrenPropName in p)) {
                p[childrenPropName] = [];
            }
            p[childrenPropName].push(item);
            if (p[collapsedPropName] === undefined) {
                p[collapsedPropName] = options?.initiallyCollapsed ?? false;
            }
        }
    });
    // we need and want the Tree Level,
    // we can do that after the tree is created and mutate the array by adding a __treeLevel property on each item
    // perhaps there might be a way to add this while creating the tree for now that is the easiest way I found
    if (Array.isArray(options?.aggregators)) {
        options.aggregators.forEach((aggregator) => {
            addTreeLevelAndAggregatorsByMutation(roots, { childrenPropName, levelPropName, aggregator }, 0);
        });
    }
    else {
        addTreeLevelByMutation(roots, { childrenPropName, levelPropName }, 0);
    }
    return roots;
}
/**
 * Find an item from a tree (hierarchical) view structure (a parent that can have children array which themseleves can children and so on)
 * @param {Array<Object>} treeArray - hierarchical tree dataset
 * @param {Function} predicate - search predicate to find the item in the hierarchical tree structure
 * @param {String} childrenPropertyName - children property name to use in the tree (defaults to "children")
 */
function findItemInTreeStructure(treeArray, predicate, childrenPropertyName) {
    if (!childrenPropertyName) {
        throw new Error('findItemInTreeStructure requires parameter "childrenPropertyName"');
    }
    const initialFind = treeArray.find(predicate);
    const elementsWithChildren = treeArray.filter((x) => childrenPropertyName in x && x[childrenPropertyName]);
    if (initialFind) {
        return initialFind;
    }
    else if (elementsWithChildren.length) {
        const childElements = [];
        for (const item of elementsWithChildren) {
            if (childrenPropertyName in item) {
                item[childrenPropertyName].forEach((el) => childElements.push(el));
            }
        }
        return findItemInTreeStructure(childElements, predicate, childrenPropertyName);
    }
    return undefined;
}
/**
 * Take a number (or a string) and display it as a formatted decimal string with defined minimum and maximum decimals
 * @param input
 * @param minDecimal
 * @param maxDecimal
 * @param decimalSeparator
 * @param thousandSeparator
 */
function decimalFormatted(input, minDecimal, maxDecimal, decimalSeparator = '.', thousandSeparator = '') {
    if (isNaN(+input)) {
        return input;
    }
    const minDec = minDecimal === undefined ? 2 : minDecimal;
    const maxDec = maxDecimal === undefined ? 2 : maxDecimal;
    let amount = String(Math.round(+input * Math.pow(10, maxDec)) / Math.pow(10, maxDec));
    if (amount.indexOf('.') < 0 && minDec > 0) {
        amount += '.';
    }
    while (amount.length - amount.indexOf('.') <= minDec) {
        amount += '0';
    }
    const decimalSplit = amount.split('.');
    let integerNumber;
    let decimalNumber;
    // do we want to display our number with a custom separator in each thousand position
    if (thousandSeparator) {
        integerNumber = decimalSplit.length >= 1 ? thousandSeparatorFormatted(decimalSplit[0], thousandSeparator) : undefined;
    }
    else {
        integerNumber = decimalSplit.length >= 1 ? decimalSplit[0] : amount;
    }
    // when using a separator that is not a dot, replace it with the new separator
    if (decimalSplit.length > 1) {
        decimalNumber = decimalSplit[1];
    }
    let output = '';
    if (integerNumber !== undefined && decimalNumber !== undefined) {
        output = `${integerNumber}${decimalSeparator}${decimalNumber}`;
    }
    else if (integerNumber !== undefined && integerNumber !== null) {
        output = integerNumber;
    }
    return output;
}
/**
 * Format a number following options passed as arguments (decimals, separator, ...)
 * @param input
 * @param minDecimal
 * @param maxDecimal
 * @param wrapNegativeNumberInBraquets
 * @param symbolPrefix
 * @param symbolSuffix
 * @param decimalSeparator
 * @param thousandSeparator
 */
function formatNumber(input, minDecimal, maxDecimal, wrapNegativeNumberInBraquets, symbolPrefix = '', symbolSuffix = '', decimalSeparator = '.', thousandSeparator = '') {
    if (isNaN(+input)) {
        return input;
    }
    const calculatedValue = Math.round(parseFloat(input) * 1000000) / 1000000;
    if (calculatedValue < 0) {
        const absValue = Math.abs(calculatedValue);
        if (wrapNegativeNumberInBraquets) {
            if (!isNaN(minDecimal) || !isNaN(maxDecimal)) {
                return `(${symbolPrefix}${decimalFormatted(absValue, minDecimal, maxDecimal, decimalSeparator, thousandSeparator)}${symbolSuffix})`;
            }
            const formattedValue = thousandSeparatorFormatted(`${absValue}`, thousandSeparator);
            return `(${symbolPrefix}${formattedValue}${symbolSuffix})`;
        }
        else {
            if (!isNaN(minDecimal) || !isNaN(maxDecimal)) {
                return `-${symbolPrefix}${decimalFormatted(absValue, minDecimal, maxDecimal, decimalSeparator, thousandSeparator)}${symbolSuffix}`;
            }
            const formattedValue = thousandSeparatorFormatted(`${absValue}`, thousandSeparator);
            return `-${symbolPrefix}${formattedValue}${symbolSuffix}`;
        }
    }
    else {
        if (!isNaN(minDecimal) || !isNaN(maxDecimal)) {
            return `${symbolPrefix}${decimalFormatted(input, minDecimal, maxDecimal, decimalSeparator, thousandSeparator)}${symbolSuffix}`;
        }
        const formattedValue = thousandSeparatorFormatted(`${input}`, thousandSeparator);
        return `${symbolPrefix}${formattedValue}${symbolSuffix}`;
    }
}
/**
 * When a queryFieldNameGetterFn is defined, then get the value from that getter callback function
 * @param {Column} columnDef
 * @param {Object} dataContext
 * @param {String} defaultValue - optional value to use if value isn't found in data context
 * @return outputValue
 */
function getCellValueFromQueryFieldGetter(columnDef, dataContext, defaultValue) {
    if (typeof columnDef.queryFieldNameGetterFn === 'function') {
        const queryFieldName = columnDef.queryFieldNameGetterFn(dataContext);
        // get the cell value from the item or when it's a dot notation then exploded the item and get the final value
        if (queryFieldName?.indexOf('.') >= 0) {
            defaultValue = getDescendantProperty(dataContext, queryFieldName);
        }
        else {
            defaultValue = dataContext.hasOwnProperty(queryFieldName) ? dataContext[queryFieldName] : defaultValue;
        }
    }
    return defaultValue;
}
/**
 * From a dot (.) notation path, find and return a property within an object given a path
 * @param object - object input
 * @param path - path of the complex object, string with dot (.) notation
 * @returns outputValue - the object property value found if any
 */
function getDescendantProperty(object, path) {
    if (!object || !path) {
        return object;
    }
    return path.split('.').reduce((obj, prop) => obj && obj[prop], object);
}
/** Get I18N Translation Prefix, defaults to an empty string */
function getTranslationPrefix(gridOptions) {
    if (gridOptions && gridOptions.translationNamespace) {
        return gridOptions.translationNamespace + (gridOptions.translationNamespaceSeparator || '');
    }
    return '';
}
/** From a column definition, find column type */
function getColumnFieldType(columnDef) {
    return columnDef.outputType || columnDef.type || index_js_1.FieldType.string;
}
/** Verify if the identified column is of type Date */
function isColumnDateType(fieldType) {
    switch (fieldType) {
        case index_js_1.FieldType.date:
        case index_js_1.FieldType.dateTime:
        case index_js_1.FieldType.dateIso:
        case index_js_1.FieldType.dateTimeIso:
        case index_js_1.FieldType.dateTimeShortIso:
        case index_js_1.FieldType.dateTimeIsoAmPm:
        case index_js_1.FieldType.dateTimeIsoAM_PM:
        case index_js_1.FieldType.dateEuro:
        case index_js_1.FieldType.dateEuroShort:
        case index_js_1.FieldType.dateTimeEuro:
        case index_js_1.FieldType.dateTimeShortEuro:
        case index_js_1.FieldType.dateTimeEuroAmPm:
        case index_js_1.FieldType.dateTimeEuroAM_PM:
        case index_js_1.FieldType.dateTimeEuroShort:
        case index_js_1.FieldType.dateTimeEuroShortAmPm:
        case index_js_1.FieldType.dateTimeEuroShortAM_PM:
        case index_js_1.FieldType.dateUs:
        case index_js_1.FieldType.dateUsShort:
        case index_js_1.FieldType.dateTimeUs:
        case index_js_1.FieldType.dateTimeShortUs:
        case index_js_1.FieldType.dateTimeUsAmPm:
        case index_js_1.FieldType.dateTimeUsAM_PM:
        case index_js_1.FieldType.dateTimeUsShort:
        case index_js_1.FieldType.dateTimeUsShortAmPm:
        case index_js_1.FieldType.dateTimeUsShortAM_PM:
        case index_js_1.FieldType.dateUtc:
            return true;
        default:
            return false;
    }
}
/**
 * Mapper for query operators (ex.: <= is "le", > is "gt")
 * @param string operator
 * @returns string map
 */
function mapOperatorType(operator) {
    let map;
    switch (operator) {
        case '<':
        case 'LT':
            map = index_js_1.OperatorType.lessThan;
            break;
        case '<=':
        case 'LE':
            map = index_js_1.OperatorType.lessThanOrEqual;
            break;
        case '>':
        case 'GT':
            map = index_js_1.OperatorType.greaterThan;
            break;
        case '>=':
        case 'GE':
            map = index_js_1.OperatorType.greaterThanOrEqual;
            break;
        case '!=':
        case 'NE':
            map = index_js_1.OperatorType.notEqual;
            break;
        case '*':
        case 'a*':
        case 'StartsWith':
            map = index_js_1.OperatorType.startsWith;
            break;
        case '*z':
        case 'EndsWith':
            map = index_js_1.OperatorType.endsWith;
            break;
        case '=':
        case '==':
        case 'EQ':
            map = index_js_1.OperatorType.equal;
            break;
        case 'IN':
            map = index_js_1.OperatorType.in;
            break;
        case 'NIN':
        case 'NOT_IN':
            map = index_js_1.OperatorType.notIn;
            break;
        case '<>':
        case 'Not_Contains':
        case 'NOT_CONTAINS':
            map = index_js_1.OperatorType.notContains;
            break;
        case 'Contains':
        case 'CONTAINS':
        default:
            map = index_js_1.OperatorType.contains;
            break;
    }
    return map;
}
/**
 * Find equivalent short designation of an Operator Type or Operator String.
 * When using a Compound Filter, we use the short designation and so we need the mapped value.
 * For example OperatorType.startsWith short designation is "a*", while OperatorType.greaterThanOrEqual is ">="
 */
function mapOperatorToShorthandDesignation(operator) {
    let shortOperator = '';
    switch (operator) {
        case index_js_1.OperatorType.greaterThan:
        case '>':
            shortOperator = '>';
            break;
        case index_js_1.OperatorType.greaterThanOrEqual:
        case '>=':
            shortOperator = '>=';
            break;
        case index_js_1.OperatorType.lessThan:
        case '<':
            shortOperator = '<';
            break;
        case index_js_1.OperatorType.lessThanOrEqual:
        case '<=':
            shortOperator = '<=';
            break;
        case index_js_1.OperatorType.notEqual:
        case '<>':
            shortOperator = '<>';
            break;
        case index_js_1.OperatorType.equal:
        case '=':
        case '==':
        case 'EQ':
            shortOperator = '=';
            break;
        case index_js_1.OperatorType.startsWith:
        case 'a*':
        case '*':
            shortOperator = 'a*';
            break;
        case index_js_1.OperatorType.endsWith:
        case '*z':
            shortOperator = '*z';
            break;
        default:
            // any other operator will be considered as already a short expression, so we can return same input operator
            shortOperator = operator;
            break;
    }
    return shortOperator;
}
/**
 * Mapper for query operator by a Filter Type
 * For example a multiple-select typically uses 'IN' operator
 * @param operator
 * @returns string map
 */
function mapOperatorByFieldType(fieldType) {
    let map;
    if (isColumnDateType(fieldType)) {
        map = index_js_1.OperatorType.equal;
    }
    else {
        switch (fieldType) {
            case index_js_1.FieldType.unknown:
            case index_js_1.FieldType.string:
            case index_js_1.FieldType.text:
            case index_js_1.FieldType.password:
            case index_js_1.FieldType.readonly:
                map = index_js_1.OperatorType.contains;
                break;
            case index_js_1.FieldType.float:
            case index_js_1.FieldType.number:
            default:
                map = index_js_1.OperatorType.equal;
                break;
        }
    }
    return map;
}
/**
 * Takes an object and allow to provide a property key to omit from the original object
 * @param {Object} obj - input object
 * @param {String} omitKey - object property key to omit
 * @returns {String} original object without the property that user wants to omit
 */
function objectWithoutKey(obj, omitKey) {
    return Object.keys(obj).reduce((result, objKey) => {
        if (objKey !== omitKey) {
            result[objKey] = obj[objKey];
        }
        return result;
    }, {});
}
/**
 * Format a number or a string into a string that is separated every thousand,
 * the default separator is a comma but user can optionally pass a different one
 * @param inputValue
 * @param separator default to comma ","
 * @returns string
 */
function thousandSeparatorFormatted(inputValue, separator = ',') {
    if (inputValue !== null && inputValue !== undefined) {
        const stringValue = `${inputValue}`;
        const decimalSplit = stringValue.split('.');
        if (decimalSplit.length === 2) {
            return `${decimalSplit[0].replace(/\B(?=(\d{3})+(?!\d))/g, separator)}.${decimalSplit[1]}`;
        }
        return stringValue.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
    }
    return inputValue;
}
/**
 * Uses the logic function to find an item in an array or returns the default
 * value provided (empty object by default)
 * @param any[] array the array to filter
 * @param function logic the logic to find the item
 * @param any [defaultVal={}] the default value to return
 * @return object the found object or default value
 */
function findOrDefault(array, logic, defaultVal = {}) {
    if (Array.isArray(array)) {
        return array.find(logic) || defaultVal;
    }
    return array;
}
/**
 * Unsubscribe all Subscriptions
 * It will return an empty array if it all went well
 * @param subscriptions
 */
function unsubscribeAll(subscriptions) {
    if (Array.isArray(subscriptions)) {
        while (subscriptions.length > 0) {
            const subscription = subscriptions.pop();
            if (subscription?.unsubscribe) {
                subscription.unsubscribe();
            }
        }
    }
    return subscriptions;
}
//# sourceMappingURL=utilities.js.map