import MetricUnitUtil from "../MetricUnitUtil";
/**
 * Convert aggregated metric results from each metric's native unit
 * (reported by OpenTelemetry / stored in MetricType) into the unit the
 * user configured in the query's alias ("legendUnit"). This is what
 * makes downstream consumers — charts, formulas, and threshold
 * comparisons — all speak the same unit as the user picked.
 *
 * Called after results are fetched but before formulas are evaluated.
 * When `legendUnit` is empty or matches the native unit (or the two
 * aren't in the same unit family), the raw value is passed through
 * unchanged, so this is always safe to call.
 */
export default class MetricResultUnitConverter {
    static convertQueryResultsToDisplayUnit(input) {
        var _a, _b, _c, _d;
        const converted = [];
        for (let index = 0; index < input.results.length; index++) {
            const rawResult = input.results[index];
            if (!rawResult) {
                converted.push({ data: [] });
                continue;
            }
            const queryConfig = input.queryConfigs[index];
            if (!queryConfig) {
                converted.push(rawResult);
                continue;
            }
            const metricName = (_c = (_b = (_a = queryConfig.metricQueryData) === null || _a === void 0 ? void 0 : _a.filterData) === null || _b === void 0 ? void 0 : _b.metricName) === null || _c === void 0 ? void 0 : _c.toString();
            const nativeUnit = metricName
                ? input.nativeUnitByMetricName.get(metricName.toLowerCase())
                : undefined;
            const displayUnit = ((_d = queryConfig.metricAliasData) === null || _d === void 0 ? void 0 : _d.legendUnit) || undefined;
            if (!nativeUnit || !displayUnit || nativeUnit === displayUnit) {
                converted.push(rawResult);
                continue;
            }
            converted.push(MetricResultUnitConverter.convertResult({
                result: rawResult,
                fromUnit: nativeUnit,
                toUnit: displayUnit,
            }));
        }
        return converted;
    }
    static convertResult(input) {
        if (input.fromUnit === input.toUnit) {
            return input.result;
        }
        const convertedData = input.result.data.map((row) => {
            const convertedValue = MetricUnitUtil.convertToMetricUnit({
                value: row.value,
                fromUnit: input.fromUnit,
                metricUnit: input.toUnit,
            });
            return Object.assign(Object.assign({}, row), { value: convertedValue });
        });
        return { data: convertedData };
    }
}
//# sourceMappingURL=MetricResultUnitConverter.js.map