"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.weightedAverage = exports.getNumericValue = void 0;
const tslib_1 = require("tslib");
const toNumber_1 = tslib_1.__importDefault(require("lodash/toNumber"));
const getNumericValue = (input) => {
    if (typeof input === 'number') {
        return input;
    }
    const numericValue = (0, toNumber_1.default)(input);
    return isNaN(numericValue) ? null : numericValue;
};
exports.getNumericValue = getNumericValue;
const weightedAverage = (params, columnId, weightColumnId) => {
    const { api: gridApi, rowNode: groupRowNode } = params;
    let weightedColumnValueSum = 0;
    let columnValueSum = 0;
    // TODO AFL: improve performance by using the intermediary aggregated values (for nested groups)
    groupRowNode.allLeafChildren.forEach((rowNode) => {
        // when editing values might be converted to strings
        const rawColumnValue = gridApi.getCellValue({ colKey: columnId, rowNode });
        const columnValue = (0, exports.getNumericValue)(rawColumnValue);
        const rawWeightedColumnValue = gridApi.getCellValue({ colKey: weightColumnId, rowNode });
        const weightedColumnValue = (0, exports.getNumericValue)(rawWeightedColumnValue);
        if (weightedColumnValue !== null) {
            weightedColumnValueSum += weightedColumnValue;
        }
        if (columnValue !== null) {
            columnValueSum += columnValue * weightedColumnValue;
        }
    });
    return {
        toString: () => {
            const result = columnValueSum / weightedColumnValueSum;
            // 0 / 0 = NaN
            if (isNaN(result)) {
                return '';
            }
            return result;
        },
        valueOf: () => {
            const result = columnValueSum / weightedColumnValueSum;
            // 0 / 0 = NaN
            if (isNaN(result)) {
                return 0;
            }
            return result;
        },
        [columnId]: columnValueSum,
        [weightColumnId]: weightedColumnValueSum,
    };
};
exports.weightedAverage = weightedAverage;
