import toNumber from 'lodash/toNumber';
export const getNumericValue = (input) => {
    if (typeof input === 'number') {
        return input;
    }
    const numericValue = toNumber(input);
    return isNaN(numericValue) ? null : numericValue;
};
function getWeightedAverageLeafNodes(gridApi, groupRowNode, filteredOnly) {
    const nodeList = (filteredOnly ? groupRowNode.childrenAfterFilter : groupRowNode.childrenAfterGroup) ?? [];
    let leafNodes = [];
    nodeList.forEach((rowNode) => {
        if (rowNode.group === true) {
            // Recursively extract leaf nodes from group
            leafNodes = leafNodes.concat(getWeightedAverageLeafNodes(gridApi, rowNode, filteredOnly));
        }
        else {
            leafNodes.push(rowNode);
        }
    });
    return leafNodes;
}
export const weightedAverage = (params, columnId, weightColumnId) => {
    const { api: gridApi, rowNode: groupRowNode } = params;
    let weightedColumnValueSum = 0;
    let columnValueSum = 0;
    const filteredOnly = !gridApi.getGridOption('suppressAggFilteredOnly');
    const leafNodes = getWeightedAverageLeafNodes(gridApi, groupRowNode, filteredOnly);
    leafNodes.forEach((rowNode) => {
        // when editing values might be converted to strings
        const rawColumnValue = gridApi.getCellValue({ colKey: columnId, rowNode });
        const columnValue = getNumericValue(rawColumnValue);
        const rawWeightedColumnValue = gridApi.getCellValue({ colKey: weightColumnId, rowNode });
        const weightedColumnValue = getNumericValue(rawWeightedColumnValue);
        if (weightedColumnValue !== null) {
            weightedColumnValueSum += weightedColumnValue;
        }
        if (columnValue !== null) {
            columnValueSum += columnValue * weightedColumnValue;
        }
    });
    let result = columnValueSum / weightedColumnValueSum;
    // 0 / 0 = NaN
    if (isNaN(result)) {
        result = 0;
    }
    return {
        // the grid by default uses toString to render values for an object, so this
        // is a trick to get the default cellRenderer to display the avg value
        toString: () => {
            return String(result);
        },
        // used for sorting
        toNumber: function () {
            return result;
        },
        [columnId]: columnValueSum,
        [weightColumnId]: weightedColumnValueSum,
    };
};
