'use strict';

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _extends = require('@babel/runtime/helpers/extends');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var capitalize = require('../../node_modules/lodash-es/capitalize.js');
var cloneDeep = require('../../node_modules/lodash-es/cloneDeep.js');
var uniqBy = require('../../node_modules/lodash-es/uniqBy.js');
var isNil = require('../../node_modules/lodash-es/isNil.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.find-index.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.iterator.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.array.sort.js');
require('core-js/modules/es.array.splice.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.regexp.to-string.js');
require('core-js/modules/es.string.includes.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 react = require('@carbon/react');
var classnames = require('classnames');
var PropTypes = require('prop-types');
var dayjs = require('../../utils/dayjs.js');
var CardPropTypes = require('../../constants/CardPropTypes.js');
var Card = require('../Card/Card.js');
var LayoutConstants = require('../../constants/LayoutConstants.js');
var StatefulTable = require('../Table/StatefulTable.js');
var timeSeriesUtils = require('../TimeSeriesCard/timeSeriesUtils.js');
var componentUtilityFunctions = require('../../utils/componentUtilityFunctions.js');
var CardToolbar = require('../Card/CardToolbar.js');
var Settings = require('../../constants/Settings.js');
var cardUtilityFunctions = require('../../utils/cardUtilityFunctions.js');
var bundledIcons = require('../../utils/bundledIcons.js');
var tableCardUtils = require('./tableCardUtils.js');
var ThresholdIcon = require('./ThresholdIcon.js');
var iconsReact = require('@carbon/icons-react');

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

var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
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 classnames__default = /*#__PURE__*/_interopDefault(classnames);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);

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__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 defaultProps = {
  size: LayoutConstants.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.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__default.default(_ref, _excluded);
  var mergedI18n = _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  var effectiveTimezone = timeZone || dayjs.default.tz.guess();
  dayjs.default.tz.setDefault(effectiveTimezone);
  dayjs.default.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 = cardUtilityFunctions.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 = cardUtilityFunctions.getUpdatedCardSize(size);

  /** adds the id to the card action */
  var cachedOnCardAction = React.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.default.createElement(typeof actionList[0].icon === 'string' ? bundledIcons.default[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.default.createElement(react.OverflowMenu, {
      className: "".concat(iotPrefix, "--table-card--overflow-menu"),
      renderIcon: function renderIcon() {
        return /*#__PURE__*/React__default.default.createElement(iconsReact.OverflowMenuVertical, {
          fill: "#5a6872",
          description: mergedI18n.overflowMenuIconDescription
        });
      }
    }, actionList.map(function (item) {
      return /*#__PURE__*/React__default.default.createElement(react.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 = cardUtilityFunctions.findMatchingThresholds(thresholds, cellItem.row, cellItem.columnId)[0];
    return matchingThresholdValue ? /*#__PURE__*/React__default.default.createElement(ThresholdIcon, _extends__default.default({
      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 = React.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 = tableCardUtils.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__default.default(missingThresholdColumns.map(function (_ref3) {
      var dataSourceId = _ref3.dataSourceId;
      return generateThresholdColumn(dataSourceId);
    }))));
  }
  var newColumns = thresholds ? columnsUpdated : columnsWithFormattedLinks;
  var filteredTimestampColumns = React.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 = React.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.default.tz(values[column]).format(defaultDateFormatPattern) : '';
        }
      });
      return _objectSpread(_objectSpread({}, row), {}, {
        values: values
      });
    });
  }, [defaultDateFormatPattern, filteredTimestampColumns, isEditable, tableData]);
  var columnsToRender = React.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 === LayoutConstants.CARD_SIZES.LARGETHIN ? '150px' : '',
        // force the text wrap
        filter: tableCardUtils.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 = React.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 === LayoutConstants.CARD_SIZES.LARGETHIN && prio !== 1 || newSize === LayoutConstants.CARD_SIZES.LARGE && !(prio === 1 || prio === 2);
      return {
        columnId: columnId,
        isHidden: isHidden
      };
    });
  }, [columnsToRender, newSize]);
  var filteredPrecisionColumns = React.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 = React.useMemo(function () {
    return isEditable ? timeSeriesUtils.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 ? cardUtilityFunctions.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] = tableCardUtils.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 = React.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 = tableCardUtils.handleExpandedItemLinks(dataItem.values, expandedItem, others.cardVariables);
      return {
        rowId: dataItem.id,
        content: /*#__PURE__*/React__default.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.default.createElement("div", {
            key: "".concat(item.id, "-expanded-").concat(index),
            className: "".concat(iotPrefix, "--table-card--expanded")
          }, item.linkTemplate ? /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement("p", {
            key: "".concat(item.id, "-label"),
            style: {
              marginRight: '5px'
            }
          }, item !== null && item !== void 0 && item.label ? item.label : '--'), /*#__PURE__*/React__default.default.createElement(react.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.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement("p", {
            key: "".concat(item.id, "-label"),
            style: {
              marginRight: '5px'
            }
          }, item !== null && item !== void 0 && item.label ? item.label : '--'), /*#__PURE__*/React__default.default.createElement("span", {
            key: "".concat(item.id, "-value")
          }, item ? dataItem.values[item.id] : null)));
        }) : /*#__PURE__*/React__default.default.createElement("div", {
          key: "".concat(dataItem.id, "-expanded"),
          className: "".concat(iotPrefix, "--table-card--expanded")
        }, ' ', /*#__PURE__*/React__default.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 !== LayoutConstants.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.default.createElement(CardToolbar.default, {
    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 ? cardUtilityFunctions.getResizeHandles(children) : [];
  return /*#__PURE__*/React__default.default.createElement(Card.default, _extends__default.default({
    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__default.default("".concat(iotPrefix, "--table-card"), className, _defineProperty__default.default({}, "".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.default.createElement(StatefulTable, {
      className: classnames__default.default("".concat(iotPrefix, "--table-card__table"), _defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default({}, "".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 componentUtilityFunctions.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.CardPropTypes), CardPropTypes.TableCardPropTypes), {
  /** Display tooltips in the table toolbar (will reset overflow property) */
  withToolbarTooltips: PropTypes__default.default.bool
});
TableCard.displayName = 'TableCard';
TableCard.defaultProps = defaultProps;
TableCard.defaultProps.i18n = _objectSpread(_objectSpread({}, defaultProps.i18n), Card.defaultProps.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;

module.exports = TableCard$1;
