"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireWildcard(require("react"));
var _utils = require("@kbn/visualizations-plugin/common/utils");
var _services = require("../services");
var _metric_value = require("./metric_value");
var _utils2 = require("../utils");
var _palette = require("../utils/palette");
var _with_auto_scale = require("./with_auto_scale");
require("./metric.scss");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const AutoScaleMetricVisValue = (0, _with_auto_scale.withAutoScale)(_metric_value.MetricVisValue);
class MetricVisComponent extends _react.Component {
  constructor(...args) {
    super(...args);
    (0, _defineProperty2.default)(this, "filterColumn", (row, metricColIndex) => {
      const {
        dimensions
      } = this.props.visParams;
      const table = this.props.visData;
      let column = dimensions.bucket ? (0, _utils.getAccessor)(dimensions.bucket) : metricColIndex;
      if (typeof column === 'object' && 'id' in column) {
        column = table.columns.indexOf(column);
      }
      this.props.fireEvent({
        name: 'filter',
        data: {
          data: [{
            table,
            column,
            row
          }]
        }
      });
    });
    (0, _defineProperty2.default)(this, "isAutoScaleWithColorizingContainer", () => {
      return this.props.visParams.metric.autoScale && this.props.visParams.metric.colorFullBackground;
    });
    (0, _defineProperty2.default)(this, "renderMetric", (metric, index, arrayRef) => {
      var _this$props$visParams, _this$props$visParams2;
      const hasBuckets = this.props.visParams.dimensions.bucket !== undefined;
      const MetricComponent = this.props.visParams.metric.autoScale ? AutoScaleMetricVisValue : _metric_value.MetricVisValue;
      return /*#__PURE__*/_react.default.createElement(MetricComponent, {
        autoScaleParams: this.isAutoScaleWithColorizingContainer() ? {
          containerStyles: {
            backgroundColor: metric.bgColor,
            minHeight: '100%',
            minWidth: '100%'
          },
          ...((_this$props$visParams = this.props.visParams.metric) !== null && _this$props$visParams !== void 0 && _this$props$visParams.autoScaleMetricAlignment ? {
            autoScaleMetricAlignment: (_this$props$visParams2 = this.props.visParams.metric) === null || _this$props$visParams2 === void 0 ? void 0 : _this$props$visParams2.autoScaleMetricAlignment
          } : {})
        } : undefined,
        key: index,
        metric: metric,
        style: this.props.visParams.metric.style,
        onFilter: hasBuckets || this.props.filterable[index] ? () => this.filterColumn(metric.rowIndex, metric.colIndex) : undefined,
        autoScale: this.props.visParams.metric.autoScale,
        colorFullBackground: this.props.visParams.metric.colorFullBackground,
        labelConfig: this.props.visParams.metric.labels,
        renderComplete: arrayRef.length - 1 === index ? this.props.renderComplete : undefined
      });
    });
  }
  getColor(value, paletteParams) {
    var _getPaletteService$ge, _getPaletteService$ge2;
    return (_getPaletteService$ge = (0, _services.getPaletteService)().get('custom')) === null || _getPaletteService$ge === void 0 ? void 0 : (_getPaletteService$ge2 = _getPaletteService$ge.getColorForValue) === null || _getPaletteService$ge2 === void 0 ? void 0 : _getPaletteService$ge2.call(_getPaletteService$ge, value, paletteParams, {
      min: paletteParams.rangeMin,
      max: paletteParams.rangeMax
    });
  }
  processTableGroups(table) {
    const {
      metric: metricConfig,
      dimensions
    } = this.props.visParams;
    const {
      percentageMode: isPercentageMode,
      style,
      palette
    } = metricConfig;
    const {
      stops = []
    } = palette !== null && palette !== void 0 ? palette : {};
    const min = stops[0];
    const max = stops[stops.length - 1];
    let bucketColumnId;
    let bucketFormatter;
    if (dimensions.bucket) {
      const bucketColumn = (0, _utils.getColumnByAccessor)(dimensions.bucket, table.columns);
      bucketColumnId = bucketColumn === null || bucketColumn === void 0 ? void 0 : bucketColumn.id;
      bucketFormatter = (0, _services.getFormatService)().deserialize((0, _utils.getFormatByAccessor)(dimensions.bucket, table.columns));
    }
    return dimensions.metrics.reduce((acc, metric) => {
      const column = (0, _utils.getColumnByAccessor)(metric, table === null || table === void 0 ? void 0 : table.columns);
      const colIndex = table === null || table === void 0 ? void 0 : table.columns.indexOf(column);
      const formatter = (0, _services.getFormatService)().deserialize((0, _utils.getFormatByAccessor)(metric, table.columns));
      const metrics = table.rows.map((row, rowIndex) => {
        var _style$labelColor, _style$bgColor, _style$bgColor2;
        let title = column.name;
        let value = row[column.id];
        const color = palette ? this.getColor(value, palette) : undefined;
        if (isPercentageMode && stops.length) {
          value = (value - min) / (max - min);
        }
        const formattedValue = (0, _utils2.formatValue)(value, formatter, 'html');
        if (bucketColumnId) {
          const bucketValue = (0, _utils2.formatValue)(row[bucketColumnId], bucketFormatter);
          title = `${bucketValue} - ${title}`;
        }
        const shouldBrush = (0, _utils2.shouldApplyColor)(color !== null && color !== void 0 ? color : '');
        return {
          label: title,
          value: formattedValue,
          color: shouldBrush && ((_style$labelColor = style.labelColor) !== null && _style$labelColor !== void 0 ? _style$labelColor : false) ? color : undefined,
          bgColor: shouldBrush && ((_style$bgColor = style.bgColor) !== null && _style$bgColor !== void 0 ? _style$bgColor : false) ? color : undefined,
          lightText: shouldBrush && ((_style$bgColor2 = style.bgColor) !== null && _style$bgColor2 !== void 0 ? _style$bgColor2 : false) && (0, _palette.needsLightText)(color),
          rowIndex,
          colIndex
        };
      });
      return [...acc, ...metrics];
    }, []);
  }
  render() {
    let metricsHtml;
    if (this.props.visData) {
      const metrics = this.processTableGroups(this.props.visData);
      metricsHtml = metrics.map(this.renderMetric);
    }
    return metricsHtml;
  }
}

// default export required for React.Lazy
// eslint-disable-next-line import/no-default-export
exports.default = MetricVisComponent;
module.exports = exports.default;