"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.DocumentCountChart = void 0;
exports.LoadingSpinner = LoadingSpinner;
var _react = _interopRequireWildcard(require("react"));
var _i18n = require("@kbn/i18n");
var _charts = require("@elastic/charts");
var _moment = _interopRequireDefault(require("moment"));
var _common = require("@kbn/charts-plugin/common");
var _eui = require("@elastic/eui");
var _kibana_context = require("../../../../kibana_context");
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; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */

const SPEC_ID = 'document_count';
function getTimezone(uiSettings) {
  if (uiSettings.isDefault('dateFormat:tz')) {
    const detectedTimezone = _moment.default.tz.guess();
    if (detectedTimezone) return detectedTimezone;else return (0, _moment.default)().format('Z');
  } else {
    return uiSettings.get('dateFormat:tz', 'Browser');
  }
}
function LoadingSpinner() {
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexItem, {
    style: {
      alignItems: 'center'
    }
  }, /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingSpinner, {
    size: "l",
    "data-test-subj": "loadingSpinner"
  }));
}
const DocumentCountChart = ({
  width,
  chartPoints,
  timeRangeEarliest,
  timeRangeLatest,
  interval,
  loading
}) => {
  const {
    services: {
      data,
      uiSettings,
      fieldFormats,
      charts
    }
  } = (0, _kibana_context.useDataVisualizerKibana)();
  const chartTheme = charts.theme.useChartsTheme();
  const chartBaseTheme = charts.theme.useChartsBaseTheme();
  const xAxisFormatter = fieldFormats.deserialize({
    id: 'date'
  });
  const useLegacyTimeAxis = uiSettings.get('visualization:useLegacyTimeAxis', false);
  const seriesName = _i18n.i18n.translate('xpack.dataVisualizer.dataGrid.field.documentCountChart.seriesLabel', {
    defaultMessage: 'document count'
  });
  const xDomain = {
    min: timeRangeEarliest,
    max: timeRangeLatest
  };
  const adjustedChartPoints = (0, _react.useMemo)(() => {
    // Display empty chart when no data in range
    if (chartPoints.length < 1) return [{
      time: timeRangeEarliest,
      value: 0
    }];

    // If chart has only one bucket
    // it won't show up correctly unless we add an extra data point
    if (chartPoints.length === 1) {
      return [...chartPoints, {
        time: interval ? Number(chartPoints[0].time) + interval : timeRangeEarliest,
        value: 0
      }];
    }
    return chartPoints;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [chartPoints, timeRangeEarliest, timeRangeLatest, interval]);
  const timefilterUpdateHandler = (0, _react.useCallback)(ranges => {
    data.query.timefilter.timefilter.setTime({
      from: (0, _moment.default)(ranges.from).toISOString(),
      to: (0, _moment.default)(ranges.to).toISOString(),
      mode: 'absolute'
    });
  }, [data]);
  const onBrushEnd = ({
    x
  }) => {
    if (!x) {
      return;
    }
    const [from, to] = x;
    timefilterUpdateHandler({
      from,
      to
    });
  };
  const onElementClick = ([elementData]) => {
    const startRange = elementData[0].x;
    const range = {
      from: startRange,
      to: startRange + interval
    };
    timefilterUpdateHandler(range);
  };
  const timeZone = getTimezone(uiSettings);
  return /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
    alignItems: "center",
    css: {
      width: width !== null && width !== void 0 ? width : '100%'
    },
    "data-test-subj": "dataVisualizerDocumentCountChart"
  }, loading ? /*#__PURE__*/_react.default.createElement(LoadingSpinner, null) : /*#__PURE__*/_react.default.createElement(_charts.Chart, {
    size: {
      width: '100%',
      height: 120
    }
  }, /*#__PURE__*/_react.default.createElement(_charts.Settings, {
    xDomain: xDomain,
    onBrushEnd: onBrushEnd,
    onElementClick: onElementClick,
    theme: chartTheme,
    baseTheme: chartBaseTheme
  }), /*#__PURE__*/_react.default.createElement(_charts.Axis, {
    id: "bottom",
    position: _charts.Position.Bottom,
    showOverlappingTicks: true,
    tickFormat: value => xAxisFormatter.convert(value)
    // temporary fix to reduce horizontal chart margin until fixed in Elastic Charts itself
    ,
    labelFormat: useLegacyTimeAxis ? undefined : () => '',
    timeAxisLayerCount: useLegacyTimeAxis ? 0 : 2,
    style: useLegacyTimeAxis ? {} : _common.MULTILAYER_TIME_AXIS_STYLE
  }), /*#__PURE__*/_react.default.createElement(_charts.Axis, {
    id: "left",
    position: _charts.Position.Left
  }), /*#__PURE__*/_react.default.createElement(_charts.HistogramBarSeries, {
    id: SPEC_ID,
    name: seriesName,
    xScaleType: _charts.ScaleType.Time,
    yScaleType: _charts.ScaleType.Linear,
    xAccessor: "time",
    yAccessors: ['value'],
    data: adjustedChartPoints,
    timeZone: timeZone,
    yNice: true
  })));
};
exports.DocumentCountChart = DocumentCountChart;