import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _extends from '@babel/runtime/helpers/extends';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import capitalize from '../../node_modules/lodash-es/capitalize.js';
import cloneDeep from '../../node_modules/lodash-es/cloneDeep.js';
import uniqBy from '../../node_modules/lodash-es/uniqBy.js';
import isNil from '../../node_modules/lodash-es/isNil.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.find.js';
import 'core-js/modules/es.array.find-index.js';
import 'core-js/modules/es.array.includes.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.array.sort.js';
import 'core-js/modules/es.array.splice.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.regexp.to-string.js';
import 'core-js/modules/es.string.includes.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import React__default, { useCallback, useMemo } from 'react';
import { Link, OverflowMenu, OverflowMenuItem } from '@carbon/react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import dayjs, { DAYJS_INPUT_FORMATS } from '../../utils/dayjs.js';
import { CardPropTypes, TableCardPropTypes } from '../../constants/CardPropTypes.js';
import Card, { defaultProps as defaultProps$1 } from '../Card/Card.js';
import { CARD_SIZES } from '../../constants/LayoutConstants.js';
import StatefulTable from '../Table/StatefulTable.js';
import { generateTableSampleValues } from '../TimeSeriesCard/timeSeriesUtils.js';
import { csvDownloadHandler } from '../../utils/componentUtilityFunctions.js';
import CardToolbar from '../Card/CardToolbar.js';
import { settings } from '../../constants/Settings.js';
import { handleCardVariables, getUpdatedCardSize, findMatchingThresholds, getResizeHandles } from '../../utils/cardUtilityFunctions.js';
import icons from '../../utils/bundledIcons.js';
import { createColumnsWithFormattedLinks, determineFilterFunction, determinePrecisionAndValue, handleExpandedItemLinks } from './tableCardUtils.js';
import ThresholdIcon from './ThresholdIcon.js';
import { OverflowMenuVertical } from '@carbon/icons-react';

var _excluded = ["id", "title", "isExpanded", "content", "children", "size", "onCardAction", "values", "filters", "isEditable", "isResizable", "i18n", "tooltip", "locale", "timeZone", "timeRange", "timeRangeOptions", "availableActions", "isLoading", "testID", "testId", "className", "renderDateDropdownInPortal", "withToolbarTooltips", "defaultDateFormatPattern", "extraActions"];
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(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.iotPrefix;
var defaultProps = {
  size: CARD_SIZES.LARGE,
  locale: 'en',
  timeZone: undefined,
  values: [],
  filters: [],
  i18n: {
    criticalLabel: 'Critical',
    moderateLabel: 'Moderate',
    lowLabel: 'Low',
    selectSeverityPlaceholder: 'Select a severity',
    searchLabel: 'Search',
    searchPlaceholder: 'Search',
    filterButtonAria: 'Filters',
    defaultFilterStringPlaceholdText: 'Type and hit enter to apply',
    downloadIconDescription: 'Download table content',
    severityLabel: 'Severity',
    emptyMessage: 'There is no data for this time range.',
    // Card-specific labels needed for combo with table toolbar
    last24HoursLabel: 'Last 24 hrs',
    last7DaysLabel: 'Last 7 days',
    lastMonthLabel: 'Last month',
    lastQuarterLabel: 'Last quarter',
    lastYearLabel: 'Last year',
    periodToDateLabel: 'Period to date',
    thisWeekLabel: 'This week',
    thisMonthLabel: 'This month',
    thisQuarterLabel: 'This quarter',
    thisYearLabel: 'This year',
    hourlyLabel: 'Hourly',
    dailyLabel: 'Daily',
    weeklyLabel: 'Weekly',
    monthlyLabel: 'Monthly',
    defaultLabel: 'Default',
    closeLabel: 'Close',
    expandLabel: 'Expand to fullscreen'
  },
  renderDateDropdownInPortal: true,
  withToolbarTooltips: false,
  defaultDateFormatPattern: DAYJS_INPUT_FORMATS.SECONDS
};
var TableCard = function TableCard(_ref) {
  var _availableActions$ran;
  var id = _ref.id,
    titleProp = _ref.title,
    isExpanded = _ref.isExpanded,
    contentProp = _ref.content,
    children = _ref.children,
    size = _ref.size,
    onCardAction = _ref.onCardAction,
    valuesProp = _ref.values,
    filters = _ref.filters,
    isEditable = _ref.isEditable,
    isResizable = _ref.isResizable,
    i18n = _ref.i18n,
    tooltip = _ref.tooltip,
    locale = _ref.locale,
    timeZone = _ref.timeZone,
    timeRange = _ref.timeRange,
    timeRangeOptions = _ref.timeRangeOptions,
    availableActions = _ref.availableActions,
    isLoading = _ref.isLoading,
    testID = _ref.testID,
    testId = _ref.testId,
    className = _ref.className,
    renderDateDropdownInPortal = _ref.renderDateDropdownInPortal,
    withToolbarTooltips = _ref.withToolbarTooltips,
    defaultDateFormatPattern = _ref.defaultDateFormatPattern,
    extraActions = _ref.extraActions,
    others = _objectWithoutProperties(_ref, _excluded);
  var mergedI18n = _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  var effectiveTimezone = timeZone || dayjs.tz.guess();
  dayjs.tz.setDefault(effectiveTimezone);
  dayjs.locale(locale);
  /** Searches for variables and updates the card if it is passed the cardVariables prop */
  // Need to skip the linkTemplate variable for now because we will handle it at render time per row
  var _handleCardVariables = handleCardVariables(titleProp, contentProp, valuesProp, others, ['href']),
    title = _handleCardVariables.title,
    _handleCardVariables$ = _handleCardVariables.content,
    _handleCardVariables$2 = _handleCardVariables$.columns,
    columns = _handleCardVariables$2 === void 0 ? [] : _handleCardVariables$2,
    showHeader = _handleCardVariables$.showHeader,
    expandedRows = _handleCardVariables$.expandedRows,
    sort = _handleCardVariables$.sort,
    thresholds = _handleCardVariables$.thresholds,
    emptyMessage = _handleCardVariables$.emptyMessage,
    data = _handleCardVariables.values;

  // Checks size property against new size naming convention and reassigns to closest supported size if necessary.
  var newSize = getUpdatedCardSize(size);

  /** adds the id to the card action */
  var cachedOnCardAction = useCallback(function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    return onCardAction.apply(void 0, [id].concat(args));
  }, [onCardAction, id]);
  var renderActionCell = function renderActionCell(_ref2) {
    var actionList = _ref2.value,
      rowId = _ref2.rowId;
    return actionList && actionList.length === 1 ? (/*#__PURE__*/React__default.createElement(typeof actionList[0].icon === 'string' ? icons[actionList[0].icon] : actionList[0].icon, {
      className: "".concat(iotPrefix, "--table-card--action-icon"),
      onClick: function onClick(evt) {
        evt.preventDefault();
        evt.stopPropagation();
        onCardAction(id, 'TABLE_CARD_ROW_ACTION', {
          rowId: rowId,
          actionId: actionList[0].id
        });
      },
      'aria-label': actionList[0].label
    })) : actionList && actionList.length > 1 ? /*#__PURE__*/React__default.createElement(OverflowMenu, {
      className: "".concat(iotPrefix, "--table-card--overflow-menu"),
      renderIcon: function renderIcon() {
        return /*#__PURE__*/React__default.createElement(OverflowMenuVertical, {
          fill: "#5a6872",
          description: mergedI18n.overflowMenuIconDescription
        });
      }
    }, actionList.map(function (item) {
      return /*#__PURE__*/React__default.createElement(OverflowMenuItem, {
        key: item.id,
        itemText: item.labelText,
        onClick: function onClick(evt) {
          evt.preventDefault();
          evt.stopPropagation();
          onCardAction(id, 'TABLE_CARD_ROW_ACTION', {
            rowId: rowId,
            actionId: item.id
          });
        }
      });
    })) : null;
  };
  var renderThresholdIcon = function renderThresholdIcon(cellItem) {
    var matchingThresholdValue = findMatchingThresholds(thresholds, cellItem.row, cellItem.columnId)[0];
    return matchingThresholdValue ? /*#__PURE__*/React__default.createElement(ThresholdIcon, _extends({
      title: "".concat(matchingThresholdValue.dataSourceId, ": ").concat(matchingThresholdValue.currentValue, " ").concat(matchingThresholdValue.comparison, " ").concat(matchingThresholdValue.value)
    }, matchingThresholdValue, {
      strings: mergedI18n,
      showSeverityLabel: matchingThresholdValue.showSeverityLabel,
      severityLabel: matchingThresholdValue.severityLabel,
      renderIconByName: others.renderIconByName
    })) : null;
  };

  // Should the table data be filtered to only match on threshold
  var uniqueThresholds = uniqBy(thresholds, 'dataSourceId');
  var onlyShowIfColumnHasData = uniqueThresholds.find(function (i) {
    return i.showOnContent;
  });
  var tableData = useMemo(function () {
    return onlyShowIfColumnHasData ? data.map(function (i) {
      return i.values[onlyShowIfColumnHasData.dataSourceId] ? i : null;
    }).filter(function (i) {
      return i;
    }) : data;
  }, [onlyShowIfColumnHasData, data]);

  // always add the last action column has default
  var actionColumn = [{
    id: 'actionColumn',
    name: '',
    width: '60px',
    isSortable: false,
    renderDataFunction: renderActionCell,
    priority: 1
  }];
  var hasActionColumn = data.filter(function (i) {
    return i.actions;
  }).length > 0;

  // If a column has a linkTemplate, format the column to render a link,
  // we need a special case here because this is the only card where we examine the actual data to replace variables in each
  var columnsWithFormattedLinks = createColumnsWithFormattedLinks(columns, defaultDateFormatPattern);

  // filter to get the indexes for each one
  var columnsUpdated = cloneDeep(columnsWithFormattedLinks);

  /**
   * Generates a threshold column based off the uniqueThreshold's value
   * @param {string} columnId AKA dataSourceId
   * @returns {Object} new column with rendered threshold
   */
  var generateThresholdColumn = function generateThresholdColumn(columnId) {
    // Need to find the index of the dataSource regardless of uniqueThresholds ordering
    // Find the matching column to get the correct label to put on the column
    var matchingColumn = columnsUpdated.find(function (column) {
      return column.dataSourceId === columnId;
    });
    var uniqueThresholdIndex = uniqueThresholds.findIndex(function (threshold) {
      return threshold.dataSourceId === columnId;
    });
    return {
      id: "iconColumn-".concat(columnId),
      label: uniqueThresholds[uniqueThresholdIndex].label ? uniqueThresholds[uniqueThresholdIndex].label : "".concat((matchingColumn === null || matchingColumn === void 0 ? void 0 : matchingColumn.label) || capitalize(columnId), " ").concat(mergedI18n.severityLabel),
      width: uniqueThresholds[uniqueThresholdIndex].width,
      isSortable: true,
      renderDataFunction: renderThresholdIcon,
      priority: 1,
      filter: {
        isMultiselect: true,
        placeholderText: mergedI18n.selectSeverityPlaceholder,
        options: [{
          id: mergedI18n.criticalLabel,
          text: mergedI18n.criticalLabel
        }, {
          id: mergedI18n.moderateLabel,
          text: mergedI18n.moderateLabel
        }, {
          id: mergedI18n.lowLabel,
          text: mergedI18n.lowLabel
        }]
      }
    };
  };

  // Add the new threshold columns to the existing columns
  uniqueThresholds.forEach(function (threshold) {
    var columnIndex = columnsUpdated.findIndex(function (column) {
      return column.dataSourceId === threshold.dataSourceId;
    });
    // If columnIndex is not -1, there was a match so add the column. Otherwise, skip the column as it will be added
    // in the next call
    if (columnIndex !== -1) {
      columnsUpdated.splice(columnIndex, 0, generateThresholdColumn(threshold.dataSourceId));
    }
  });

  // Check for any threshold columns that weren't matched (if the column was hidden) and add to the end of the array
  var missingThresholdColumns = uniqueThresholds.filter(function (threshold) {
    return !columnsUpdated.find(function (column) {
      return threshold.dataSourceId === column.dataSourceId;
    });
  });
  if (missingThresholdColumns.length > 0) {
    columnsUpdated.splice.apply(columnsUpdated, [columnsUpdated.length, 0].concat(_toConsumableArray(missingThresholdColumns.map(function (_ref3) {
      var dataSourceId = _ref3.dataSourceId;
      return generateThresholdColumn(dataSourceId);
    }))));
  }
  var newColumns = thresholds ? columnsUpdated : columnsWithFormattedLinks;
  var filteredTimestampColumns = useMemo(function () {
    return columns.map(function (column) {
      return column.type && column.type === 'TIMESTAMP' ? column.dataSourceId : null;
    }).filter(function (i) {
      return !isNil(i);
    });
  }, [columns]);
  var updatedTableData = useMemo(function () {
    return tableData.map(function (row) {
      var values = _objectSpread({}, row.values);
      Object.keys(values).forEach(function (column) {
        if (!isEditable && filteredTimestampColumns.includes(column)) {
          values[column] = values[column] ? dayjs.tz(values[column]).format(defaultDateFormatPattern) : '';
        }
      });
      return _objectSpread(_objectSpread({}, row), {}, {
        values: values
      });
    });
  }, [defaultDateFormatPattern, filteredTimestampColumns, isEditable, tableData]);
  var columnsToRender = useMemo(function () {
    return newColumns.map(function (i) {
      return _objectSpread(_objectSpread({}, i), {}, {
        id: i.dataSourceId ? i.dataSourceId : i.id,
        name: i.label ? i.label : i.dataSourceId || '',
        // don't force label to be required
        isSortable: true,
        width: i.width ? "".concat(i.width, "px") : newSize === CARD_SIZES.LARGETHIN ? '150px' : '',
        // force the text wrap
        filter: determineFilterFunction(i, mergedI18n.defaultFilterStringPlaceholdText, defaultDateFormatPattern),
        renderDataFunction: i.renderDataFunction // use the default render function of the column
        ? i.renderDataFunction : function (_ref4 // default render function is to handle timestamp
        ) {
          var value = _ref4.value;
          return (
            // if it's a timestamp column type make sure to format it
            isNil(value) ? '' : value.toString()
          );
        }
      });
    }).concat(hasActionColumn ? actionColumn : []);
  }, [actionColumn, defaultDateFormatPattern, hasActionColumn, mergedI18n.defaultFilterStringPlaceholdText, newColumns, newSize]);
  var ordering = useMemo(function () {
    return columnsToRender.map(function (_ref5) {
      var columnId = _ref5.id,
        priority = _ref5.priority;
      var prio = priority || 1; // default to 1 if not provided
      var isHidden = newSize === CARD_SIZES.LARGETHIN && prio !== 1 || newSize === CARD_SIZES.LARGE && !(prio === 1 || prio === 2);
      return {
        columnId: columnId,
        isHidden: isHidden
      };
    });
  }, [columnsToRender, newSize]);
  var filteredPrecisionColumns = useMemo(function () {
    return columns.map(function (column) {
      return column.precision ? {
        dataSourceId: column.dataSourceId,
        precision: column.precision
      } : null;
    }).filter(function (i) {
      return !isNil(i);
    });
  }, [columns]);

  // Map from threshold severity number to label
  var thresholdSeverityLabelsMap = {
    1: mergedI18n.criticalLabel,
    2: mergedI18n.moderateLabel,
    3: mergedI18n.lowLabel
  };

  // if we're in editable mode, generate fake data
  var tableDataWithTimestamp = useMemo(function () {
    return isEditable ? generateTableSampleValues(id, columns) : hasActionColumn || filteredPrecisionColumns.length || thresholds ? updatedTableData.map(function (i) {
      // if has custom action
      var action = hasActionColumn ? {
        actionColumn: i.actions || []
      } : null;
      var matchingThresholds = thresholds ? findMatchingThresholds(thresholds, i.values) : null;

      // map each of the matching thresholds into a data object
      var iconColumns = matchingThresholds ? matchingThresholds.reduce(function (thresholdData, threshold) {
        thresholdData["iconColumn-".concat(threshold.dataSourceId)] =
        // eslint-disable-line no-param-reassign
        thresholdSeverityLabelsMap[threshold.severity];
        return thresholdData;
      }, {}) : null;

      // if column have custom precision value
      var precisionUpdated = filteredPrecisionColumns.length ? Object.keys(i.values).reduce(function (acc, value) {
        var precision = filteredPrecisionColumns.find(function (item) {
          return item.dataSourceId === value;
        });

        // If I find a precision column it should override the normal
        if (precision) {
          acc[value] = determinePrecisionAndValue(precision.precision, i.values[value], locale);
        }
        return acc;
      }, {}) : null;
      return {
        id: i.id,
        values: _objectSpread(_objectSpread(_objectSpread(_objectSpread(_objectSpread({}, iconColumns), action), i.values), action), precisionUpdated),
        isSelectable: false
      };
    }) : updatedTableData;
  }, [isEditable, id, columns, hasActionColumn, filteredPrecisionColumns, thresholds, updatedTableData, thresholdSeverityLabelsMap, locale]);

  // format expanded rows to send to Table component
  var expandedRowsFormatted = useMemo(function () {
    return expandedRows && expandedRows.length ? updatedTableData.map(function (dataItem) {
      // filter the data keys and find the expandaded row exist for that key
      var expandedItem = Object.keys(dataItem.values).map(function (value) {
        return expandedRows.filter(function (item) {
          return item.id === value;
        })[0];
      }).filter(function (i) {
        return i;
      });

      // add links and link variables to the expandedItem
      var formattedExpandedItems = handleExpandedItemLinks(dataItem.values, expandedItem, others.cardVariables);
      return {
        rowId: dataItem.id,
        content: /*#__PURE__*/React__default.createElement("div", {
          key: "".concat(dataItem.id, "-expanded"),
          className: "".concat(iotPrefix, "--table-card--expanded-row-content")
        }, formattedExpandedItems.length ? formattedExpandedItems.map(function (item, index) {
          return /*#__PURE__*/React__default.createElement("div", {
            key: "".concat(item.id, "-expanded-").concat(index),
            className: "".concat(iotPrefix, "--table-card--expanded")
          }, item.linkTemplate ? /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("p", {
            key: "".concat(item.id, "-label"),
            style: {
              marginRight: '5px'
            }
          }, item !== null && item !== void 0 && item.label ? item.label : '--'), /*#__PURE__*/React__default.createElement(Link, {
            key: "".concat(item.id, "-link"),
            href: item.linkTemplate.href,
            target: item.linkTemplate.target ? item.linkTemplate.target : null
          }, dataItem.values[item.id])) : /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement("p", {
            key: "".concat(item.id, "-label"),
            style: {
              marginRight: '5px'
            }
          }, item !== null && item !== void 0 && item.label ? item.label : '--'), /*#__PURE__*/React__default.createElement("span", {
            key: "".concat(item.id, "-value")
          }, item ? dataItem.values[item.id] : null)));
        }) : /*#__PURE__*/React__default.createElement("div", {
          key: "".concat(dataItem.id, "-expanded"),
          className: "".concat(iotPrefix, "--table-card--expanded")
        }, ' ', /*#__PURE__*/React__default.createElement("p", {
          key: "".concat(dataItem.id, "-label")
        }, "--")))
      };
    }) : [];
  }, [expandedRows, others.cardVariables, updatedTableData]);

  // is columns recieved is different from the columnsToRender show card expand
  var isExpandable = !!ordering.find(function (col) {
    return col.isHidden;
  });
  var hasFilter = newSize !== CARD_SIZES.LARGETHIN;
  var hasRowExpansion = !!(expandedRows && expandedRows.length);

  // Defined the first column to be sorted, if column has defined sort
  var columnStartSortDefined = columnsToRender.find(function (item) {
    return item.sort;
  });

  // if not sort by column provided, sort on the first priority 1 column
  var columnStartSort = !columnStartSortDefined ? columnsToRender.find(function (item) {
    return item.priority === 1;
  }) : columnStartSortDefined;
  var mergedAvailableActions = _objectSpread(_objectSpread({}, availableActions), {}, {
    expand: isExpandable,
    range: (_availableActions$ran = availableActions === null || availableActions === void 0 ? void 0 : availableActions.range) !== null && _availableActions$ran !== void 0 ? _availableActions$ran : true
  });
  var cardToolbar = /*#__PURE__*/React__default.createElement(CardToolbar, {
    availableActions: mergedAvailableActions,
    i18n: mergedI18n,
    isEditable: isEditable,
    isExpanded: isExpanded,
    onCardAction: cachedOnCardAction,
    width: newSize.width,
    timeRange: timeRange,
    timeRangeOptions: timeRangeOptions,
    renderDateDropdownInPortal: renderDateDropdownInPortal,
    locale: locale,
    timeZone: effectiveTimezone,
    id: id,
    extraActions: extraActions
  });
  var resizeHandles = isResizable ? getResizeHandles(children) : [];
  return /*#__PURE__*/React__default.createElement(Card, _extends({
    id: id,
    size: newSize,
    onCardAction: onCardAction,
    availableActions: {
      expand: isExpandable,
      range: true
    },
    isEditable: isEditable,
    isResizable: isResizable,
    isExpanded: isExpanded,
    i18n: mergedI18n,
    locale: locale,
    timeZone: effectiveTimezone,
    resizeHandles: resizeHandles,
    hideHeader: true,
    className: classnames("".concat(iotPrefix, "--table-card"), className, _defineProperty({}, "".concat(iotPrefix, "--table-card--with-tooltips"), withToolbarTooltips))
    // Use the Table's loading state rather than Card's
    ,
    isLoading: false
    // TODO: remove deprecated testID in v3.
    ,
    testId: testID || testId
  }, others), function (_ref6) {
    var height = _ref6.height;
    var numberOfRowsPerPage = Math.max(!isNil(height) && height !== 0 ? Math.floor((height - 56) / 56) : 10, 1 // at least pass 1 row per page
    );
    return /*#__PURE__*/React__default.createElement(StatefulTable, {
      className: classnames("".concat(iotPrefix, "--table-card__table"), _defineProperty(_defineProperty(_defineProperty({}, "".concat(iotPrefix, "--table-card__table--expanded"), isExpanded), "".concat(iotPrefix, "--table-card__table--hide-header"), showHeader !== undefined ? !showHeader : false), "".concat(iotPrefix, "--table-card__table--with-data"), (data === null || data === void 0 ? void 0 : data.length) > 0)),
      columns: columnsToRender,
      data: tableDataWithTimestamp,
      id: "table-for-card-".concat(id),
      key: "table-for-card-".concat(numberOfRowsPerPage, "-").concat(columnsToRender === null || columnsToRender === void 0 ? void 0 : columnsToRender.length),
      isExpanded: isExpanded,
      secondaryTitle: title,
      tooltip: tooltip,
      options: {
        hasPagination: true,
        hasSearch: !isEditable,
        // Remove search bar on preview mode. https://github.ibm.com/wiotp/monitoring-dashboard/issues/1749
        hasFilter: hasFilter,
        hasRowExpansion: hasRowExpansion
      },
      locale: locale,
      expandedData: expandedRowsFormatted,
      actions: {
        table: {
          onRowClicked: function onRowClicked() {},
          onRowExpanded: function onRowExpanded() {},
          onChangeSort: function onChangeSort() {}
        },
        pagination: {
          onChangePage: function onChangePage() {}
        },
        toolbar: {
          onClearAllFilters: function onClearAllFilters() {},
          onToggleFilter: function onToggleFilter() {},
          onDownloadCSV: function onDownloadCSV(filteredData) {
            return csvDownloadHandler(filteredData, title);
          }
        }
      },
      view: {
        pagination: {
          pageSize: numberOfRowsPerPage,
          pageSizes: [numberOfRowsPerPage, 25, 100],
          isItemPerPageHidden: !isExpanded
        },
        toolbar: {
          activeBar: null,
          isDisabled: isEditable,
          customToolbarContent: cardToolbar
        },
        filters: filters,
        table: _objectSpread(_objectSpread({}, columnStartSort ? {
          sort: {
            columnId: columnStartSort.id,
            direction: !columnStartSortDefined ? sort : columnStartSortDefined.sort
          }
        } : {}), {}, {
          emptyState: {
            message: emptyMessage || mergedI18n.emptyMessage
          },
          loadingState: {
            isLoading: isLoading,
            rowCount: 7
          },
          ordering: ordering
        })
      },
      showHeader: showHeader !== undefined ? showHeader : true,
      i18n: mergedI18n // TODO: add Card defaultprops ?
    });
  });
};
TableCard.propTypes = _objectSpread(_objectSpread(_objectSpread({}, CardPropTypes), TableCardPropTypes), {
  /** Display tooltips in the table toolbar (will reset overflow property) */
  withToolbarTooltips: PropTypes.bool
});
TableCard.displayName = 'TableCard';
TableCard.defaultProps = defaultProps;
TableCard.defaultProps.i18n = _objectSpread(_objectSpread({}, defaultProps.i18n), defaultProps$1.i18n);
TableCard.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TableCard",
  "props": {
    "size": {
      "defaultValue": {
        "value": "CARD_SIZES.LARGE",
        "computed": true
      },
      "required": false
    },
    "locale": {
      "defaultValue": {
        "value": "'en'",
        "computed": false
      },
      "required": false
    },
    "timeZone": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "required": false
    },
    "values": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "required": false
    },
    "filters": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  criticalLabel: 'Critical',\n  moderateLabel: 'Moderate',\n  lowLabel: 'Low',\n  selectSeverityPlaceholder: 'Select a severity',\n  searchLabel: 'Search',\n  searchPlaceholder: 'Search',\n  filterButtonAria: 'Filters',\n  defaultFilterStringPlaceholdText: 'Type and hit enter to apply',\n  downloadIconDescription: 'Download table content',\n  severityLabel: 'Severity',\n  emptyMessage: 'There is no data for this time range.',\n  // Card-specific labels needed for combo with table toolbar\n  last24HoursLabel: 'Last 24 hrs',\n  last7DaysLabel: 'Last 7 days',\n  lastMonthLabel: 'Last month',\n  lastQuarterLabel: 'Last quarter',\n  lastYearLabel: 'Last year',\n  periodToDateLabel: 'Period to date',\n  thisWeekLabel: 'This week',\n  thisMonthLabel: 'This month',\n  thisQuarterLabel: 'This quarter',\n  thisYearLabel: 'This year',\n  hourlyLabel: 'Hourly',\n  dailyLabel: 'Daily',\n  weeklyLabel: 'Weekly',\n  monthlyLabel: 'Monthly',\n  defaultLabel: 'Default',\n  closeLabel: 'Close',\n  expandLabel: 'Expand to fullscreen',\n}",
        "computed": false
      },
      "required": false
    },
    "renderDateDropdownInPortal": {
      "defaultValue": {
        "value": "true",
        "computed": false
      },
      "required": false
    },
    "withToolbarTooltips": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "Display tooltips in the table toolbar (will reset overflow property)",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "defaultDateFormatPattern": {
      "defaultValue": {
        "value": "DAYJS_INPUT_FORMATS.SECONDS",
        "computed": true
      },
      "required": false
    }
  },
  "composes": ["../../constants/CardPropTypes"]
};
var TableCard$1 = TableCard;

export { TableCard$1 as default };
