"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useColumnChart = exports.hoveredRow$ = exports.getXScaleType = exports.getLegendText = exports.getFieldType = exports.BAR_COLOR = void 0;
var _moment = _interopRequireDefault(require("moment"));
var _rxjs = require("rxjs");
var _react = _interopRequireDefault(require("react"));
var _useObservable = _interopRequireDefault(require("react-use/lib/useObservable"));
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _public = require("@kbn/data-plugin/public");
var _mlDataGrid = require("@kbn/ml-data-grid");
/*
 * 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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const NON_AGGREGATABLE = 'non-aggregatable';
const hoveredRow$ = new _rxjs.BehaviorSubject(null);
exports.hoveredRow$ = hoveredRow$;
const BAR_COLOR = (0, _eui.euiPaletteColorBlind)()[0];
exports.BAR_COLOR = BAR_COLOR;
const BAR_COLOR_BLUR = (0, _eui.euiPaletteColorBlind)({
  rotations: 2
})[10];
const getXScaleType = kbnFieldType => {
  switch (kbnFieldType) {
    case _public.KBN_FIELD_TYPES.BOOLEAN:
    case _public.KBN_FIELD_TYPES.IP:
    case _public.KBN_FIELD_TYPES.STRING:
      return 'ordinal';
    case _public.KBN_FIELD_TYPES.DATE:
      return 'time';
    case _public.KBN_FIELD_TYPES.NUMBER:
      return 'linear';
  }
};
exports.getXScaleType = getXScaleType;
const getFieldType = schema => {
  if (schema === NON_AGGREGATABLE) {
    return undefined;
  }
  let fieldType;
  switch (schema) {
    case 'datetime':
      fieldType = _public.KBN_FIELD_TYPES.DATE;
      break;
    case 'numeric':
      fieldType = _public.KBN_FIELD_TYPES.NUMBER;
      break;
    case 'boolean':
      fieldType = _public.KBN_FIELD_TYPES.BOOLEAN;
      break;
    case 'json':
      fieldType = _public.KBN_FIELD_TYPES.OBJECT;
      break;
    default:
      fieldType = _public.KBN_FIELD_TYPES.STRING;
  }
  return fieldType;
};
exports.getFieldType = getFieldType;
const getLegendText = (chartData, maxChartColumns, isNumeric = false) => {
  if (chartData.type === 'unsupported') {
    return _i18n.i18n.translate('xpack.dataVisualizer.dataGridChart.histogramNotAvailable', {
      defaultMessage: 'Chart not supported.'
    });
  }
  if (chartData.data.length === 0) {
    return '';
  }
  if (chartData.type === 'boolean') {
    var _chartData$data$0$key, _chartData$data$0$key2, _chartData$data$1$key, _chartData$data$1$key2;
    return /*#__PURE__*/_react.default.createElement("table", null, /*#__PURE__*/_react.default.createElement("tbody", null, /*#__PURE__*/_react.default.createElement("tr", null, chartData.data[0] !== undefined && /*#__PURE__*/_react.default.createElement("td", {
      className: "dataGridChart__legendBoolean"
    }, (_chartData$data$0$key = (_chartData$data$0$key2 = chartData.data[0].key_as_string) === null || _chartData$data$0$key2 === void 0 ? void 0 : _chartData$data$0$key2.slice(0, 1)) !== null && _chartData$data$0$key !== void 0 ? _chartData$data$0$key : ''), chartData.data[1] !== undefined && /*#__PURE__*/_react.default.createElement("td", {
      className: "dataGridChart__legendBoolean"
    }, (_chartData$data$1$key = (_chartData$data$1$key2 = chartData.data[1].key_as_string) === null || _chartData$data$1$key2 === void 0 ? void 0 : _chartData$data$1$key2.slice(0, 1)) !== null && _chartData$data$1$key !== void 0 ? _chartData$data$1$key : ''))));
  }
  if ((0, _mlDataGrid.isOrdinalChartData)(chartData) && isNumeric) {
    // The original data could be numerical but also ordinal (e.g. "2340")
    return _i18n.i18n.translate('xpack.dataVisualizer.dataGridChart.singleTopValueLegend', {
      defaultMessage: `{cardinality, plural, one {# value {exampleValue}} other {# values}}`,
      values: {
        cardinality: chartData.cardinality,
        exampleValue: chartData.data[0].key ? `(${chartData.data[0].key})` : ''
      }
    });
  }
  if ((0, _mlDataGrid.isOrdinalChartData)(chartData) && chartData.cardinality <= maxChartColumns) {
    return _i18n.i18n.translate('xpack.dataVisualizer.dataGridChart.singleCategoryLegend', {
      defaultMessage: `{cardinality, plural, one {# category} other {# categories}}`,
      values: {
        cardinality: chartData.cardinality
      }
    });
  }
  if ((0, _mlDataGrid.isOrdinalChartData)(chartData) && chartData.cardinality > maxChartColumns) {
    return _i18n.i18n.translate('xpack.dataVisualizer.dataGridChart.topCategoriesLegend', {
      defaultMessage: `top {maxChartColumns} of {cardinality} categories`,
      values: {
        cardinality: chartData.cardinality,
        maxChartColumns
      }
    });
  }
  if ((0, _mlDataGrid.isNumericChartData)(chartData)) {
    const fromValue = Math.round(chartData.stats[0] * 100) / 100;
    const toValue = Math.round(chartData.stats[1] * 100) / 100;
    return fromValue !== toValue ? `${fromValue} - ${toValue}` : '' + fromValue;
  }
  return '';
};
exports.getLegendText = getLegendText;
const useColumnChart = (chartData, columnType, maxChartColumns, isNumeric) => {
  const fieldType = getFieldType(columnType.schema);
  const hoveredRow = (0, _useObservable.default)(hoveredRow$);
  const xScaleType = getXScaleType(fieldType);
  const getColor = d => {
    if (hoveredRow === undefined || hoveredRow === null) {
      return BAR_COLOR;
    }
    if ((0, _mlDataGrid.isOrdinalChartData)(chartData) && xScaleType === 'ordinal' && hoveredRow._source[columnType.id] === d.key) {
      return BAR_COLOR;
    }
    if ((0, _mlDataGrid.isNumericChartData)(chartData) && xScaleType === 'linear' && hoveredRow._source[columnType.id] >= +d.key && hoveredRow._source[columnType.id] < +d.key + chartData.interval) {
      return BAR_COLOR;
    }
    if ((0, _mlDataGrid.isNumericChartData)(chartData) && xScaleType === 'time' && (0, _moment.default)(hoveredRow._source[columnType.id]).unix() * 1000 >= +d.key && (0, _moment.default)(hoveredRow._source[columnType.id]).unix() * 1000 < +d.key + chartData.interval) {
      return BAR_COLOR;
    }
    return BAR_COLOR_BLUR;
  };
  let data = [];

  // The if/else if/else is a work-around because `.map()` doesn't work with union types.
  // See TS Caveats for details: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-3.html#caveats
  if ((0, _mlDataGrid.isOrdinalChartData)(chartData)) {
    data = chartData.data.map((d, idx) => {
      var _d$key_as_string;
      return {
        ...d,
        x: idx,
        key_as_string: (_d$key_as_string = d.key_as_string) !== null && _d$key_as_string !== void 0 ? _d$key_as_string : d.key,
        color: getColor(d)
      };
    });
  } else if ((0, _mlDataGrid.isNumericChartData)(chartData)) {
    data = chartData.data.map((d, idx) => ({
      ...d,
      x: idx,
      key_as_string: d.key_as_string || d.key,
      color: getColor(d)
    }));
  }
  return {
    data,
    legendText: getLegendText(chartData, maxChartColumns, isNumeric),
    xScaleType
  };
};
exports.useColumnChart = useColumnChart;