'use strict';

var _extends = require('@babel/runtime/helpers/extends');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var isEqual = require('../../node_modules/lodash-es/isEqual.js');
var defaultsDeep = require('../../node_modules/lodash-es/defaultsDeep.js');
var capitalize = require('../../node_modules/lodash-es/capitalize.js');
var omit = require('../../node_modules/lodash-es/omit.js');
var isEmpty = require('../../node_modules/lodash-es/isEmpty.js');
var isNil = require('../../node_modules/lodash-es/isNil.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.from.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.array.iterator.js');
require('core-js/modules/es.array.join.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.array.sort.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.object.values.js');
require('core-js/modules/es.set.js');
require('core-js/modules/es.string.includes.js');
require('core-js/modules/es.string.iterator.js');
require('core-js/modules/web.dom-collections.for-each.js');
require('core-js/modules/web.dom-collections.iterator.js');
var React = require('react');
var PropTypes = require('prop-types');
var classnames = require('classnames');
var chartsReact = require('@carbon/charts-react');
var componentUtilityFunctions = require('../../utils/componentUtilityFunctions.js');
var CardPropTypes = require('../../constants/CardPropTypes.js');
var LayoutConstants = require('../../constants/LayoutConstants.js');
var Card = require('../Card/Card.js');
var StatefulTable = require('../Table/StatefulTable.js');
var Settings = require('../../constants/Settings.js');
var cardUtilityFunctions = require('../../utils/cardUtilityFunctions.js');
var deprecate = require('../../internal/deprecate.js');
var dayjs = require('../../utils/dayjs.js');
var usePrevious = require('../../hooks/usePrevious.js');
var timeSeriesUtils = require('./timeSeriesUtils.js');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var _excluded = ["title", "content", "children", "size", "interval", "isEditable", "isResizable", "values", "locale", "timeZone", "i18n", "isExpanded", "timeRange", "isLazyLoading", "isLoading", "domainRange", "tooltipDateFormatPattern", "tooltipShowTotals", "showTimeInGMT", "testID", "testId", "defaultDateFormatPattern"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var iotPrefix = Settings.settings.iotPrefix;
var TimeSeriesDatasetPropTypes = PropTypes__default.default.shape({
  label: PropTypes__default.default.string.isRequired,
  /** the attribute in values to map to */
  dataSourceId: PropTypes__default.default.string.isRequired,
  /** optional filter to apply to this particular line */
  dataFilter: PropTypes__default.default.objectOf(PropTypes__default.default.any),
  /** optional param to disable DataFilter */
  disableDataFilter: PropTypes__default.default.bool,
  /** optional param to set the colors */
  color: PropTypes__default.default.string
});
var TimeSeriesCardPropTypes = {
  content: PropTypes__default.default.shape({
    series: PropTypes__default.default.oneOfType([TimeSeriesDatasetPropTypes, PropTypes__default.default.arrayOf(TimeSeriesDatasetPropTypes)]).isRequired,
    /** Custom X-axis label */
    xLabel: PropTypes__default.default.string,
    /** Custom Y-axis label */
    yLabel: PropTypes__default.default.string,
    /** the number of decimals to show in the legend and on the y-axis */
    decimalPrecision: PropTypes__default.default.number,
    /** Optionally hide zero. Useful when chart values are not close to zero, giving a better view of the meaningful data */
    includeZeroOnXaxis: PropTypes__default.default.bool,
    /** Optionally hide zero. Useful when chart values are not close to zero, giving a better view of the meaningful data */
    includeZeroOnYaxis: PropTypes__default.default.bool,
    /** Which attribute is the time attribute i.e. 'timestamp' */
    timeDataSourceId: PropTypes__default.default.string,
    /** should it be a line chart or bar chart, default is line chart */
    chartType: deprecate(PropTypes__default.default.oneOf(Object.values(LayoutConstants.TIME_SERIES_TYPES)), '\nThe prop `chartType` for Card has been deprecated. BarChartCard now handles all bar chart functionality including time-based bar charts.'),
    /** optional units to put in the legend */
    unit: PropTypes__default.default.string,
    /** Optionally adds a zoom bar to the chart */
    zoomBar: CardPropTypes.ZoomBarPropTypes,
    /** Number of grid-line spaces to the left and right of the chart to add white space to. Defaults to 1 */
    addSpaceOnEdges: PropTypes__default.default.number,
    /** whether or not to show a legend at the bottom of the card
     * if not explicitly stated, the card will show based on the length of the series
     */
    showLegend: PropTypes__default.default.bool,
    /** Where to place the chart legend */
    legendPosition: PropTypes__default.default.string,
    /** carbon charts legend truncation options */
    truncation: CardPropTypes.TruncationPropTypes,
    /** if there are alerts associated with this chart (used to markup datapoints), this is a start/end set of alert ranges for each alert */
    alertRanges: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
      endTimestamp: PropTypes__default.default.number,
      startTimestamp: PropTypes__default.default.number,
      /** color of the alert */
      color: PropTypes__default.default.string,
      /** more information about the alert */
      details: PropTypes__default.default.string
    })),
    /** set of thresholds these render dotted lines on the graph to indicate that the line values might be crossing logical thresholds */
    thresholds: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
      axis: PropTypes__default.default.oneOf(['x', 'y']),
      value: PropTypes__default.default.number,
      label: PropTypes__default.default.string,
      fillColor: PropTypes__default.default.string
    }))
  }).isRequired,
  i18n: PropTypes__default.default.shape({
    alertDetected: PropTypes__default.default.string,
    noData: PropTypes__default.default.string,
    tooltipGroupLabel: PropTypes__default.default.string,
    defaultFilterStringPlaceholdText: PropTypes__default.default.string
  }),
  /** array of data from the backend for instance [{timestamp: Date object || ms timestamp, temperature: 35, humidity: 10}, ...] */
  values: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
    timestamp: PropTypes__default.default.oneOfType([PropTypes__default.default.number, PropTypes__default.default.string, PropTypes__default.default.instanceOf(Date)])
  })),
  cardVariables: PropTypes__default.default.objectOf(PropTypes__default.default.oneOfType([PropTypes__default.default.string, PropTypes__default.default.func, PropTypes__default.default.number, PropTypes__default.default.bool])),
  /** Interval for time series configuration used for formatting the x-axis */
  interval: PropTypes__default.default.oneOf(['minute', 'hour', 'day', 'week', 'quarter', 'month', 'year']),
  /** optional domain to graph from. First value is the beginning of the range. Second value is the end of the range
   * can be date instance or timestamp
   */
  domainRange: PropTypes__default.default.arrayOf(PropTypes__default.default.oneOfType([PropTypes__default.default.number, PropTypes__default.default.object])),
  /** Region for value and text formatting */
  locale: PropTypes__default.default.string,
  /** Show timestamp in browser local time or GMT */
  showTimeInGMT: PropTypes__default.default.bool,
  size: function size(props, propName, componentName) {
    var error;
    if (!Object.keys(LayoutConstants.CARD_SIZES).includes(props[propName])) {
      error = new Error("`".concat(componentName, "` prop `").concat(propName, "` must be one of ").concat(Object.keys(LayoutConstants.CARD_SIZES).join(','), "."));
    }
    // If the size
    if (props[propName] === LayoutConstants.CARD_SIZES.SMALL || props[propName] === LayoutConstants.CARD_SIZES.SMALLWIDE || props[propName] === LayoutConstants.CARD_SIZES.SMALLFULL) {
      error = new Error("Deprecation notice: `".concat(componentName, "` prop `").concat(propName, "` cannot be `").concat(props[propName], "` as the charts will not render correctly. Minimum size is `MEDIUM`"));
    }
    return error;
  },
  /** tooltip format pattern that follows the dayjs formatting patterns */
  tooltipDateFormatPattern: PropTypes__default.default.string,
  /** should the tooltip total the line chart values? */
  tooltipShowTotals: PropTypes__default.default.bool,
  // TODO: remove deprecated 'testID' in v3
  // eslint-disable-next-line react/require-default-props
  testID: deprecate(PropTypes__default.default.string, "The 'testID' prop has been deprecated. Please use 'testId' instead."),
  testId: PropTypes__default.default.string,
  /** default date format pattern that follows the dayjs formatting patterns */
  defaultDateFormatPattern: PropTypes__default.default.string
};
var defaultProps = {
  size: LayoutConstants.CARD_SIZES.MEDIUM,
  values: [],
  i18n: {
    alertDetected: 'Alert detected:',
    noDataLabel: 'No data is available for this time range.',
    tooltipGroupLabel: 'Group',
    defaultFilterStringPlaceholdText: 'Filter'
  },
  chartType: LayoutConstants.TIME_SERIES_TYPES.LINE,
  locale: 'en',
  timeZone: undefined,
  content: {
    series: [],
    timeDataSourceId: 'timestamp',
    includeZeroOnXaxis: false,
    includeZeroOnYaxis: false,
    showLegend: true,
    legendPosition: 'bottom',
    truncation: {
      type: 'end_line',
      threshold: 20,
      numCharacter: 20
    }
  },
  interval: 'hour',
  showTimeInGMT: false,
  domainRange: null,
  tooltipDateFormatPattern: dayjs.DAYJS_INPUT_FORMATS.SECONDS,
  tooltipShowTotals: true,
  defaultDateFormatPattern: dayjs.DAYJS_INPUT_FORMATS.SECONDS
};
var TimeSeriesCard = function TimeSeriesCard(_ref) {
  var titleProp = _ref.title,
    content = _ref.content,
    children = _ref.children,
    size = _ref.size,
    interval = _ref.interval,
    isEditable = _ref.isEditable,
    isResizable = _ref.isResizable,
    initialValues = _ref.values,
    locale = _ref.locale,
    timeZone = _ref.timeZone,
    i18n = _ref.i18n,
    isExpanded = _ref.isExpanded,
    timeRange = _ref.timeRange,
    isLazyLoading = _ref.isLazyLoading,
    isLoading = _ref.isLoading,
    domainRange = _ref.domainRange,
    tooltipDateFormatPattern = _ref.tooltipDateFormatPattern,
    tooltipShowTotals = _ref.tooltipShowTotals,
    showTimeInGMT = _ref.showTimeInGMT,
    testID = _ref.testID,
    testId = _ref.testId,
    defaultDateFormatPattern = _ref.defaultDateFormatPattern,
    others = _objectWithoutProperties__default.default(_ref, _excluded);
  var effectiveTimezone = timeZone || dayjs.default.tz.guess();
  dayjs.default.tz.setDefault(effectiveTimezone);
  dayjs.default.locale(locale);
  // need to deep merge the nested content default props as default props only uses a shallow merge natively
  var contentWithDefaults = React.useMemo(function () {
    return defaultsDeep({}, content, defaultProps.content);
  }, [content]);
  var mergedI18n = React.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var _handleCardVariables = cardUtilityFunctions.handleCardVariables(titleProp, contentWithDefaults, initialValues, others),
    title = _handleCardVariables.title,
    _handleCardVariables$ = _handleCardVariables.content,
    series = _handleCardVariables$.series,
    timeDataSourceId = _handleCardVariables$.timeDataSourceId,
    alertRanges = _handleCardVariables$.alertRanges,
    xLabel = _handleCardVariables$.xLabel,
    yLabel = _handleCardVariables$.yLabel,
    includeZeroOnXaxis = _handleCardVariables$.includeZeroOnXaxis,
    includeZeroOnYaxis = _handleCardVariables$.includeZeroOnYaxis,
    decimalPrecision = _handleCardVariables$.decimalPrecision,
    unit = _handleCardVariables$.unit,
    chartType = _handleCardVariables$.chartType,
    zoomBar = _handleCardVariables$.zoomBar,
    showLegend = _handleCardVariables$.showLegend,
    legendPosition = _handleCardVariables$.legendPosition,
    addSpaceOnEdges = _handleCardVariables$.addSpaceOnEdges,
    truncation = _handleCardVariables$.truncation,
    thresholds = _handleCardVariables$.thresholds,
    valuesProp = _handleCardVariables.values;
  var chartRef = React.useRef(null);
  var previousTick = React.useRef();
  // Workaround since downstream consumers might keep regenerating the series object and useMemo does a direct in-memory comparison for the object
  var objectAgnosticSeries = JSON.stringify(series);
  var objectAgnosticThresholds = JSON.stringify(thresholds);
  var sampleValues = React.useMemo(function () {
    return isEditable ? timeSeriesUtils.generateSampleValues(series, timeDataSourceId, interval, timeRange, thresholds) : [];
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [objectAgnosticSeries, timeDataSourceId, interval, timeRange, objectAgnosticThresholds, isEditable]);
  var values = React.useMemo(function () {
    return isEditable ? sampleValues : valuesProp;
  }, [isEditable, sampleValues, valuesProp]);

  // Unfortunately the API returns the data out of order sometimes
  var valueSort = React.useMemo(function () {
    return values.sort(function (left, right) {
      return dayjs.default.utc(left[timeDataSourceId]).diff(dayjs.default.utc(right[timeDataSourceId]));
    });
  }, [values, timeDataSourceId]);

  // Checks size property against new size naming convention and reassigns to closest supported size if necessary.
  var newSize = React.useMemo(function () {
    return cardUtilityFunctions.getUpdatedCardSize(size);
  }, [size]);
  var maxTicksPerSize = React.useMemo(function () {
    switch (newSize) {
      case LayoutConstants.CARD_SIZES.MEDIUMTHIN:
        return 2;
      case LayoutConstants.CARD_SIZES.MEDIUM:
        return 4;
      case LayoutConstants.CARD_SIZES.MEDIUMWIDE:
      case LayoutConstants.CARD_SIZES.LARGE:
      case LayoutConstants.CARD_SIZES.LARGETHIN:
        return 6;
      case LayoutConstants.CARD_SIZES.LARGEWIDE:
        return 14;
      default:
        return 10;
    }
  }, [newSize]);
  var formatTick = React.useCallback(
  /** *
   * timestamp of current value
   * index of current value
   * ticks: array of current ticks
   */
  function (timestamp, index, ticks) {
    var previousTimestamp = previousTick.current;
    // store current in the previous tick
    previousTick.current = timestamp;
    return timeSeriesUtils.formatGraphTick(timestamp, index, ticks, interval, locale, previousTimestamp, showTimeInGMT);
  }, [interval, locale, showTimeInGMT]);

  // Set the colors for each dataset
  var colors = React.useMemo(function () {
    return timeSeriesUtils.formatColors(series);
  }, [series]);

  /** This caches the chart value */
  var chartData = React.useMemo(function () {
    return timeSeriesUtils.formatChartData(timeDataSourceId, series, valueSort);
  }, [timeDataSourceId, series, valueSort]);
  var previousChartData = usePrevious.usePrevious(chartData);

  /** This is needed to update the chart when the lines and values change */
  React.useEffect(function () {
    var _chartRef$current;
    if (chartRef !== null && chartRef !== void 0 && (_chartRef$current = chartRef.current) !== null && _chartRef$current !== void 0 && _chartRef$current.chart && !isEqual(chartData, previousChartData)) {
      chartRef.current.chart.model.setData(chartData);
    }
  }, [chartData, previousChartData]);
  var isChartDataEmpty = isEmpty(chartData);
  var _useMemo = React.useMemo(function () {
      var columnNamesSet = new Set();
      var tableValues = valueSort.map(function (value, index) {
        Object.keys(omit(value, timeDataSourceId)).forEach(function (key) {
          return columnNamesSet.add(key);
        });
        return {
          id: "dataindex-".concat(index),
          values: _objectSpread(_objectSpread({}, omit(value, timeDataSourceId)), {}, _defineProperty__default.default({}, timeDataSourceId, dayjs.default.tz(value[timeDataSourceId]).format(defaultDateFormatPattern))),
          isSelectable: false
        };
      });
      return {
        tableData: tableValues,
        columnNames: Array.from(columnNamesSet)
      };
    }, [defaultDateFormatPattern, timeDataSourceId, valueSort]),
    tableData = _useMemo.tableData,
    columnNames = _useMemo.columnNames;

  // In expanded mode we show the data underneath the linechart in a table so need to build the columns
  var tableColumns = React.useMemo(function () {
    // First column is timestamp
    var columns = [{
      id: timeDataSourceId,
      name: capitalize(timeDataSourceId),
      isSortable: true,
      type: 'TIMESTAMP'
    }];
    // then the rest in series order
    return columns.concat(columnNames.map(function (columnName) {
      var matchingDataSource = Array.isArray(series) ? series.find(function (d) {
        return d.dataSourceId === columnName;
      }) : series;
      return {
        id: columnName,
        // use the label if one exists as it will be the user-defined, readable name
        // UNLESS dataFilter is enabled as the matchingDataSource will only find the first match
        name: matchingDataSource ? matchingDataSource.dataFilter ? matchingDataSource.dataSourceId : matchingDataSource.label : columnName,
        isSortable: true,
        filter: {
          placeholderText: mergedI18n.defaultFilterStringPlaceholdText
        },
        renderDataFunction: function renderDataFunction(_ref2) {
          var value = _ref2.value;
          if (typeof value === 'number' && !isNil(decimalPrecision)) {
            return cardUtilityFunctions.chartValueFormatter(value, size, unit, locale, decimalPrecision);
          }
          return value;
        }
      };
    }));
  }, [columnNames, decimalPrecision, mergedI18n.defaultFilterStringPlaceholdText, locale, series, size, timeDataSourceId, unit]);

  // TODO: remove in next release
  var ChartComponent = chartType === LayoutConstants.TIME_SERIES_TYPES.BAR ? chartsReact.StackedBarChart : chartsReact.LineChart;
  var resizeHandles = isResizable ? cardUtilityFunctions.getResizeHandles(children) : [];
  var handleStrokeColor = React.useMemo(function () {
    return timeSeriesUtils.applyStrokeColor(alertRanges);
  }, [alertRanges]);
  var handleFillColor = React.useMemo(function () {
    return timeSeriesUtils.applyFillColor(alertRanges);
  }, [alertRanges]);
  var handleIsFilled = React.useMemo(function () {
    return timeSeriesUtils.applyIsFilled(alertRanges);
  }, [alertRanges]);
  var options = React.useMemo(function () {
    return _objectSpread(_objectSpread({
      animations: false,
      accessibility: false,
      axes: {
        bottom: _objectSpread(_objectSpread({
          title: xLabel || ' ',
          mapsTo: 'date',
          scaleType: 'time',
          ticks: {
            number: maxTicksPerSize,
            formatter: formatTick
          }
        }, thresholds !== null && thresholds !== void 0 && thresholds.some(function (threshold) {
          return threshold.axis === 'x';
        }) ? {
          thresholds: thresholds === null || thresholds === void 0 ? void 0 : thresholds.filter(function (threshold) {
            return threshold.axis === 'x';
          })
        } : {}), {}, {
          includeZero: includeZeroOnXaxis
        }, domainRange ? {
          domain: domainRange
        } : {}),
        left: _objectSpread(_objectSpread({
          title: "".concat(yLabel || '', " ").concat(unit ? "(".concat(unit, ")") : ''),
          mapsTo: 'value',
          ticks: {
            formatter: function formatter(axisValue) {
              return cardUtilityFunctions.chartValueFormatter(axisValue, newSize, null, locale, decimalPrecision);
            }
          }
        }, thresholds !== null && thresholds !== void 0 && thresholds.some(function (threshold) {
          return threshold.axis === 'y';
        }) ? {
          thresholds: thresholds === null || thresholds === void 0 ? void 0 : thresholds.filter(function (threshold) {
            return threshold.axis === 'y';
          })
        } : {}), {}, {
          stacked: chartType === LayoutConstants.TIME_SERIES_TYPES.BAR && series.length > 1,
          includeZero: includeZeroOnYaxis,
          scaleType: 'linear'
        })
      },
      legend: {
        position: legendPosition,
        clickable: !isEditable,
        enabled: showLegend !== null && showLegend !== void 0 ? showLegend : series.length > 1,
        truncation: truncation
      },
      containerResizable: true,
      tooltip: {
        showTotal: tooltipShowTotals,
        truncation: {
          type: 'none'
        },
        valueFormatter: function valueFormatter(tooltipValue) {
          return cardUtilityFunctions.chartValueFormatter(tooltipValue, newSize, unit, locale, decimalPrecision);
        },
        customHTML: function customHTML() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          return cardUtilityFunctions.handleTooltip.apply(void 0, args.concat([alertRanges, mergedI18n.alertDetected, showTimeInGMT, tooltipDateFormatPattern, locale]));
        },
        groupLabel: mergedI18n.tooltipGroupLabel
      },
      getStrokeColor: handleStrokeColor,
      getFillColor: handleFillColor,
      getIsFilled: handleIsFilled,
      color: colors
    }, zoomBar !== null && zoomBar !== void 0 && zoomBar.enabled && (LayoutConstants.ZOOM_BAR_ENABLED_CARD_SIZES.includes(size) || isExpanded) ? {
      zoomBar: {
        // [zoomBar.axes]: {    TODO: the top axis is the only axis supported at the moment so default to top
        top: {
          enabled: zoomBar.enabled,
          initialZoomDomain: zoomBar.initialZoomDomain,
          type: zoomBar.view || 'slider_view' // default to slider view
        }
      }
    } : {}), {}, {
      timeScale: {
        addSpaceOnEdges: !isNil(addSpaceOnEdges) ? addSpaceOnEdges : 1
      },
      toolbar: {
        enabled: false
      }
    });
  }, [xLabel, maxTicksPerSize, formatTick, thresholds, includeZeroOnXaxis, domainRange, yLabel, unit, chartType, series.length, includeZeroOnYaxis, legendPosition, isEditable, showLegend, truncation, tooltipShowTotals, mergedI18n.tooltipGroupLabel, mergedI18n.alertDetected, handleStrokeColor, handleFillColor, handleIsFilled, colors, zoomBar, size, isExpanded, addSpaceOnEdges, newSize, locale, decimalPrecision, alertRanges, showTimeInGMT, tooltipDateFormatPattern]);
  return /*#__PURE__*/React__default.default.createElement(Card.default, _extends__default.default({
    title: title,
    size: newSize,
    i18n: mergedI18n,
    timeRange: timeRange
  }, others, {
    locale: locale,
    timeZone: effectiveTimezone,
    isExpanded: isExpanded,
    isEditable: isEditable,
    isEmpty: isChartDataEmpty,
    isLazyLoading: isLazyLoading || valueSort && valueSort.length > 200,
    isLoading: isLoading,
    resizeHandles: resizeHandles,
    testId: testID || testId
  }), !isChartDataEmpty ? /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement("div", {
    className: classnames__default.default("".concat(iotPrefix, "--time-series-card--wrapper"), _defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default({}, "".concat(iotPrefix, "--time-series-card--wrapper__expanded"), isExpanded), "".concat(iotPrefix, "--time-series-card--wrapper__lots-of-points"), valueSort && valueSort.length > 50), "".concat(iotPrefix, "--time-series-card--wrapper__editable"), isEditable))
  }, /*#__PURE__*/React__default.default.createElement(ChartComponent, {
    ref: chartRef,
    data: chartData,
    options: options,
    width: "100%",
    height: "100%",
    key: "thresholds-key".concat(thresholds !== null && thresholds !== void 0 && thresholds.length ? objectAgnosticThresholds : '') // have to regen the component if thresholds change
  })), isExpanded ? /*#__PURE__*/React__default.default.createElement(StatefulTable, {
    testId: "".concat(testId, "-table"),
    id: "TimeSeries-table",
    className: "".concat(iotPrefix, "--time-series-card--stateful-table"),
    columns: tableColumns,
    data: tableData,
    options: {
      hasPagination: true,
      hasSearch: true,
      hasFilter: true
    },
    actions: {
      toolbar: {
        onDownloadCSV: function onDownloadCSV(filteredData) {
          return componentUtilityFunctions.csvDownloadHandler(filteredData, title);
        }
      }
    },
    view: {
      pagination: {
        pageSize: 10,
        pageSizes: [10, 20, 30]
      },
      toolbar: {
        activeBar: null
      },
      filters: [],
      table: {
        sort: {
          columnId: timeDataSourceId,
          direction: 'DESC'
        },
        emptyState: {
          message: mergedI18n.noDataLabel
        }
      }
    },
    i18n: mergedI18n
  }) : null) : null);
};
TimeSeriesCard.propTypes = _objectSpread(_objectSpread({}, CardPropTypes.CardPropTypes), TimeSeriesCardPropTypes);
TimeSeriesCard.defaultProps = defaultProps;
TimeSeriesCard.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TimeSeriesCard",
  "props": {
    "size": {
      "defaultValue": {
        "value": "CARD_SIZES.MEDIUM",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "custom",
        "raw": "(props, propName, componentName) => {\n  let error;\n  if (!Object.keys(CARD_SIZES).includes(props[propName])) {\n    error = new Error(\n      `\\`${componentName}\\` prop \\`${propName}\\` must be one of ${Object.keys(CARD_SIZES).join(\n        ','\n      )}.`\n    );\n  }\n  // If the size\n  if (\n    props[propName] === CARD_SIZES.SMALL ||\n    props[propName] === CARD_SIZES.SMALLWIDE ||\n    props[propName] === CARD_SIZES.SMALLFULL\n  ) {\n    error = new Error(\n      `Deprecation notice: \\`${componentName}\\` prop \\`${propName}\\` cannot be \\`${props[propName]}\\` as the charts will not render correctly. Minimum size is \\`MEDIUM\\``\n    );\n  }\n  return error;\n}"
      },
      "required": false
    },
    "values": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "array of data from the backend for instance [{timestamp: Date object || ms timestamp, temperature: 35, humidity: 10}, ...]",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "shape",
          "value": {
            "timestamp": {
              "name": "union",
              "value": [{
                "name": "number"
              }, {
                "name": "string"
              }, {
                "name": "instanceOf",
                "value": "Date"
              }],
              "required": false
            }
          }
        }
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  alertDetected: 'Alert detected:',\n  noDataLabel: 'No data is available for this time range.',\n  tooltipGroupLabel: 'Group',\n  defaultFilterStringPlaceholdText: 'Filter',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "alertDetected": {
            "name": "string",
            "required": false
          },
          "noData": {
            "name": "string",
            "required": false
          },
          "tooltipGroupLabel": {
            "name": "string",
            "required": false
          },
          "defaultFilterStringPlaceholdText": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "chartType": {
      "defaultValue": {
        "value": "TIME_SERIES_TYPES.LINE",
        "computed": true
      },
      "required": false
    },
    "locale": {
      "defaultValue": {
        "value": "'en'",
        "computed": false
      },
      "description": "Region for value and text formatting",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "timeZone": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "required": false
    },
    "content": {
      "defaultValue": {
        "value": "{\n  series: [],\n  timeDataSourceId: 'timestamp',\n  includeZeroOnXaxis: false,\n  includeZeroOnYaxis: false,\n  showLegend: true,\n  legendPosition: 'bottom',\n  truncation: {\n    type: 'end_line',\n    threshold: 20,\n    numCharacter: 20,\n  },\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "series": {
            "name": "union",
            "value": [{
              "name": "custom",
              "raw": "TimeSeriesDatasetPropTypes"
            }, {
              "name": "arrayOf",
              "value": {
                "name": "custom",
                "raw": "TimeSeriesDatasetPropTypes"
              }
            }],
            "required": true
          },
          "xLabel": {
            "name": "string",
            "description": "Custom X-axis label",
            "required": false
          },
          "yLabel": {
            "name": "string",
            "description": "Custom Y-axis label",
            "required": false
          },
          "decimalPrecision": {
            "name": "number",
            "description": "the number of decimals to show in the legend and on the y-axis",
            "required": false
          },
          "includeZeroOnXaxis": {
            "name": "bool",
            "description": "Optionally hide zero. Useful when chart values are not close to zero, giving a better view of the meaningful data",
            "required": false
          },
          "includeZeroOnYaxis": {
            "name": "bool",
            "description": "Optionally hide zero. Useful when chart values are not close to zero, giving a better view of the meaningful data",
            "required": false
          },
          "timeDataSourceId": {
            "name": "string",
            "description": "Which attribute is the time attribute i.e. 'timestamp'",
            "required": false
          },
          "chartType": {
            "name": "custom",
            "raw": "deprecate(\n  PropTypes.oneOf(Object.values(TIME_SERIES_TYPES)),\n  '\\nThe prop `chartType` for Card has been deprecated. BarChartCard now handles all bar chart functionality including time-based bar charts.'\n)",
            "description": "should it be a line chart or bar chart, default is line chart",
            "required": false
          },
          "unit": {
            "name": "string",
            "description": "optional units to put in the legend",
            "required": false
          },
          "zoomBar": {
            "name": "custom",
            "raw": "ZoomBarPropTypes",
            "description": "Optionally adds a zoom bar to the chart",
            "required": false
          },
          "addSpaceOnEdges": {
            "name": "number",
            "description": "Number of grid-line spaces to the left and right of the chart to add white space to. Defaults to 1",
            "required": false
          },
          "showLegend": {
            "name": "bool",
            "description": "whether or not to show a legend at the bottom of the card\nif not explicitly stated, the card will show based on the length of the series",
            "required": false
          },
          "legendPosition": {
            "name": "string",
            "description": "Where to place the chart legend",
            "required": false
          },
          "truncation": {
            "name": "custom",
            "raw": "TruncationPropTypes",
            "description": "carbon charts legend truncation options",
            "required": false
          },
          "alertRanges": {
            "name": "arrayOf",
            "value": {
              "name": "shape",
              "value": {
                "endTimestamp": {
                  "name": "number",
                  "required": false
                },
                "startTimestamp": {
                  "name": "number",
                  "required": false
                },
                "color": {
                  "name": "string",
                  "description": "color of the alert",
                  "required": false
                },
                "details": {
                  "name": "string",
                  "description": "more information about the alert",
                  "required": false
                }
              }
            },
            "description": "if there are alerts associated with this chart (used to markup datapoints), this is a start/end set of alert ranges for each alert",
            "required": false
          },
          "thresholds": {
            "name": "arrayOf",
            "value": {
              "name": "shape",
              "value": {
                "axis": {
                  "name": "enum",
                  "value": [{
                    "value": "'x'",
                    "computed": false
                  }, {
                    "value": "'y'",
                    "computed": false
                  }],
                  "required": false
                },
                "value": {
                  "name": "number",
                  "required": false
                },
                "label": {
                  "name": "string",
                  "required": false
                },
                "fillColor": {
                  "name": "string",
                  "required": false
                }
              }
            },
            "description": "set of thresholds these render dotted lines on the graph to indicate that the line values might be crossing logical thresholds",
            "required": false
          }
        }
      },
      "required": false
    },
    "interval": {
      "defaultValue": {
        "value": "'hour'",
        "computed": false
      },
      "description": "Interval for time series configuration used for formatting the x-axis",
      "type": {
        "name": "enum",
        "value": [{
          "value": "'minute'",
          "computed": false
        }, {
          "value": "'hour'",
          "computed": false
        }, {
          "value": "'day'",
          "computed": false
        }, {
          "value": "'week'",
          "computed": false
        }, {
          "value": "'quarter'",
          "computed": false
        }, {
          "value": "'month'",
          "computed": false
        }, {
          "value": "'year'",
          "computed": false
        }]
      },
      "required": false
    },
    "showTimeInGMT": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Show timestamp in browser local time or GMT",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "domainRange": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "optional domain to graph from. First value is the beginning of the range. Second value is the end of the range\ncan be date instance or timestamp",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "union",
          "value": [{
            "name": "number"
          }, {
            "name": "object"
          }]
        }
      },
      "required": false
    },
    "tooltipDateFormatPattern": {
      "defaultValue": {
        "value": "DAYJS_INPUT_FORMATS.SECONDS",
        "computed": true
      },
      "description": "tooltip format pattern that follows the dayjs formatting patterns",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "tooltipShowTotals": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "description": "should the tooltip total the line chart values?",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "defaultDateFormatPattern": {
      "defaultValue": {
        "value": "DAYJS_INPUT_FORMATS.SECONDS",
        "computed": true
      },
      "description": "default date format pattern that follows the dayjs formatting patterns",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "cardVariables": {
      "description": "",
      "type": {
        "name": "objectOf",
        "value": {
          "name": "union",
          "value": [{
            "name": "string"
          }, {
            "name": "func"
          }, {
            "name": "number"
          }, {
            "name": "bool"
          }]
        }
      },
      "required": false
    },
    "testID": {
      "description": "",
      "type": {
        "name": "custom",
        "raw": "deprecate(\n  PropTypes.string,\n  `The 'testID' prop has been deprecated. Please use 'testId' instead.`\n)"
      },
      "required": false
    },
    "testId": {
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    }
  },
  "composes": ["../../constants/CardPropTypes"]
};
var TimeSeriesCard$1 = TimeSeriesCard;

module.exports = TimeSeriesCard$1;
