'use strict';

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var omit = require('../../../../../node_modules/lodash-es/omit.js');
var isEmpty = require('../../../../../node_modules/lodash-es/isEmpty.js');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
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.includes.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.symbol.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.string.includes.js');
require('core-js/modules/web.dom-collections.for-each.js');
var React = require('react');
var PropTypes = require('prop-types');
var uuid = require('uuid');
var hash = require('object-hash');
var react = require('@carbon/react');
var Settings = require('../../../../../constants/Settings.js');
var editorUtils = require('../../../../DashboardEditor/editorUtils.js');
var Button = require('../../../../Button/Button.js');
var List = require('../../../../List/List.js');
var DataSeriesFormItemModal = require('../DataSeriesFormItemModal.js');
var ContentFormItemTitle = require('../ContentFormItemTitle.js');
var LayoutConstants = require('../../../../../constants/LayoutConstants.js');
var DataSeriesFormContent = require('../DataSeriesFormItems/DataSeriesFormContent.js');
var HierarchyDataFormItems = require('../HierarchyDataFormItems/HierarchyDataFormItems.js');
var iconsReact = require('@carbon/icons-react');

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

var _asyncToGenerator__default = /*#__PURE__*/_interopDefault(_asyncToGenerator);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefault(_regeneratorRuntime);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var hash__default = /*#__PURE__*/_interopDefault(hash);

var _excluded = ["thresholds"];
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 propTypes = {
  cardConfig: PropTypes__default.default.shape({
    id: PropTypes__default.default.string,
    title: PropTypes__default.default.string,
    size: PropTypes__default.default.oneOf(Object.keys(LayoutConstants.CARD_SIZES)),
    type: PropTypes__default.default.oneOf([LayoutConstants.CARD_TYPES.TABLE]),
    content: PropTypes__default.default.shape({
      columns: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
        label: PropTypes__default.default.string,
        dataSourceId: PropTypes__default.default.string,
        type: PropTypes__default.default.string,
        dataItemType: PropTypes__default.default.string
      })),
      thresholds: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
        color: PropTypes__default.default.string,
        comparison: PropTypes__default.default.string,
        dataSourceId: PropTypes__default.default.string,
        icon: PropTypes__default.default.string,
        value: PropTypes__default.default.oneOfType([PropTypes__default.default.number, PropTypes__default.default.string, PropTypes__default.default.bool])
      }))
    }),
    dataSource: PropTypes__default.default.shape({
      groupBy: PropTypes__default.default.arrayOf(PropTypes__default.default.string)
    })
  }),
  /* callback when any changes are made to the card config, the full updated card JSON is passed as the argument */
  onChange: PropTypes__default.default.func.isRequired,
  i18n: PropTypes__default.default.shape({
    dataItemEditorTitle: PropTypes__default.default.string,
    dataItemEditorDataItemTitle: PropTypes__default.default.string,
    dataItemEditorDimensionTitle: PropTypes__default.default.string,
    dataItemEditorDataItemLabel: PropTypes__default.default.string,
    dataItemEditorLegendColor: PropTypes__default.default.string,
    tableColumnEditorSectionTitle: PropTypes__default.default.string,
    dataItemEditorSectionTableTooltipText: PropTypes__default.default.string,
    dataSeriesTitle: PropTypes__default.default.string,
    selectDataItems: PropTypes__default.default.string,
    selectGroupByDimensions: PropTypes__default.default.string,
    dataItem: PropTypes__default.default.string,
    edit: PropTypes__default.default.string,
    remove: PropTypes__default.default.string,
    customize: PropTypes__default.default.string
  }),
  /** an array of dataItems to be included on each card */
  dataItems: editorUtils.DataItemsPropTypes,
  /** if provided, returns an array of strings which are the dataItems to be allowed
   * on each card
   * getValidDataItems(card, selectedTimeRange)
   */
  getValidDataItems: PropTypes__default.default.func,
  /** an object where the keys are available dimensions and the values are the values available for those dimensions
   *  ex: { manufacturer: ['Rentech', 'GHI Industries'], deviceid: ['73000', '73001', '73002'] }
   */
  availableDimensions: PropTypes__default.default.shape({}),
  selectedTimeRange: PropTypes__default.default.string.isRequired,
  /** list of dataItem names that have been selected to display on the card */
  selectedDataItems: PropTypes__default.default.arrayOf(PropTypes__default.default.string),
  /** the callback is called with a list of the new data item names selected */
  setSelectedDataItems: PropTypes__default.default.func.isRequired,
  /** optional link href's for each card type that will appear in a tooltip */
  dataSeriesItemLinks: PropTypes__default.default.shape({
    table: PropTypes__default.default.string
  }),
  translateWithId: PropTypes__default.default.func.isRequired,
  actions: editorUtils.DashboardEditorActionsPropTypes
};
var defaultProps = {
  cardConfig: {},
  i18n: {
    dataItemEditorTitle: 'Edit data series',
    dataItemEditorDataItemTitle: 'Data item',
    dataItemEditorDimensionTitle: 'Group by',
    dataItemEditorDataItemLabel: 'Label',
    dataItemEditorLegendColor: 'Legend color',
    tableColumnEditorSectionTitle: 'Columns',
    dataItemEditorSectionTableTooltipText: 'Display metrics in columns. Filter the metrics by dimensions or device ID from Group by.',
    selectDataItems: 'Select data item(s)',
    selectGroupByDimensions: 'Select dimension(s)',
    dataItem: 'Data item',
    edit: 'Edit',
    remove: 'Remove',
    filter: 'Filter',
    customize: 'Customize'
  },
  dataItems: [],
  getValidDataItems: null,
  selectedDataItems: [],
  availableDimensions: {},
  dataSeriesItemLinks: null,
  actions: editorUtils.defaultDashboardEditorActionsProps
};
var TableCardFormContent = function TableCardFormContent(_ref) {
  var cardConfig = _ref.cardConfig,
    dataItems = _ref.dataItems,
    getValidDataItems = _ref.getValidDataItems,
    _onChange = _ref.onChange,
    selectedTimeRange = _ref.selectedTimeRange,
    selectedDataItems = _ref.selectedDataItems,
    setSelectedDataItems = _ref.setSelectedDataItems,
    availableDimensions = _ref.availableDimensions,
    i18n = _ref.i18n,
    dataSeriesItemLinks = _ref.dataSeriesItemLinks,
    translateWithId = _ref.translateWithId,
    actions = _ref.actions;
  var onEditDataItem = actions.onEditDataItem;
  var mergedI18n = _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  var _cardConfig$content = cardConfig.content,
    columns = _cardConfig$content.columns,
    thresholds = _cardConfig$content.thresholds;
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    showEditor = _useState2[0],
    setShowEditor = _useState2[1];
  // Need to keep track of the data item that's currently being edited so the detailed modal knows which one to show
  var _useState3 = React.useState({}),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    editDataItem = _useState4[0],
    setEditDataItem = _useState4[1];

  // Initialize the selected columns if its not currently set
  var dataSection = React.useMemo(function () {
    var a = Array.isArray(columns) ? columns.map(function (column) {
      var filteredThresholds = (thresholds === null || thresholds === void 0 ? void 0 : thresholds.filter(function (threshold) {
        return column.dataSourceId === threshold.dataSourceId;
      })) || [];
      return _objectSpread(_objectSpread({}, column), !isEmpty(filteredThresholds) // only set thresholds if they exist
      ? {
        thresholds: filteredThresholds
      } : {});
    }) : [];
    return a;
  }, [columns, thresholds]);
  var baseClassName = "".concat(iotPrefix, "--card-edit-form");

  // find valid dimension data item names
  var validDimensions = React.useMemo(function () {
    return Object.keys(availableDimensions).map(function (i) {
      return {
        id: i,
        text: i
      };
    });
  }, [availableDimensions]);
  var initialSelectedDimensions = React.useMemo(function () {
    var _cardConfig$dataSourc, _cardConfig$dataSourc2;
    return (_cardConfig$dataSourc = cardConfig === null || cardConfig === void 0 || (_cardConfig$dataSourc2 = cardConfig.dataSource) === null || _cardConfig$dataSourc2 === void 0 || (_cardConfig$dataSourc2 = _cardConfig$dataSourc2.groupBy) === null || _cardConfig$dataSourc2 === void 0 ? void 0 : _cardConfig$dataSourc2.map(function (dataSourceId) {
      return {
        id: dataSourceId,
        text: dataSourceId
      };
    })) !== null && _cardConfig$dataSourc !== void 0 ? _cardConfig$dataSourc : [];
  }, [cardConfig]);
  var validDataItems = getValidDataItems ? getValidDataItems(cardConfig, selectedTimeRange) : dataItems;
  var handleOnDataSeriesChange = function handleOnDataSeriesChange(_ref2) {
    var selectedItem = _ref2.selectedItem;
    // ignore the extra value added by the "enter" keypress
    if (selectedItem && !isEmpty(selectedItem.id)) {
      var itemWithMetaData = validDataItems === null || validDataItems === void 0 ? void 0 : validDataItems.find(function (_ref3) {
        var dataItemId = _ref3.dataItemId;
        return dataItemId === selectedItem.id;
      });
      var selectedItems = [].concat(_toConsumableArray__default.default(dataSection), [_objectSpread(_objectSpread({}, itemWithMetaData && _objectSpread({}, itemWithMetaData)), {}, {
        // create a unique dataSourceId if it's going into the attributes section
        // if it's going into the groupBy section, then just use the dataItemId
        dataSourceId: (itemWithMetaData === null || itemWithMetaData === void 0 ? void 0 : itemWithMetaData.destination) === 'groupBy' ? selectedItem.id : "".concat(selectedItem.id, "_").concat(uuid.v4())
      })]);
      var newCard = editorUtils.handleDataSeriesChange(selectedItems, cardConfig, null, null);
      setSelectedDataItems(selectedItems.map(function (_ref4) {
        var text = _ref4.text;
        return text;
      }));
      _onChange(newCard);
    }
  };
  var handleHierarchyDataItemChange = React.useCallback(function (items) {
    var updatedItems = items.map(function (item) {
      return _objectSpread(_objectSpread({}, item), {}, {
        // create a unique dataSourceId if it's going into attributes
        // if it's going into the groupBy section then just use the dataItem ID
        dataSourceId: "".concat(item.dataItemId, "_").concat(uuid.v4())
      });
    });
    var selectedItems = [].concat(_toConsumableArray__default.default(dataSection), _toConsumableArray__default.default(updatedItems));
    var newCard = editorUtils.handleDataSeriesChange(selectedItems, cardConfig, null, null);
    setSelectedDataItems(selectedItems.map(function (_ref5) {
      var text = _ref5.text;
      return text;
    }));
    _onChange(newCard);
  }, [cardConfig, dataSection, _onChange, setSelectedDataItems]);

  // need to handle thresholds from the DataSeriesFormItemModal and convert it to the right format
  var handleDataItemModalChanges = React.useCallback(function (card) {
    var _card$content, _thresholds$filter, _card$content2;
    // Get datasource from columns with thresholds
    var columnThresholdDataSource = (card === null || card === void 0 || (_card$content = card.content) === null || _card$content === void 0 || (_card$content = _card$content.columns) === null || _card$content === void 0 || (_card$content = _card$content.filter(function (column) {
      var _column$thresholds;
      return column === null || column === void 0 || (_column$thresholds = column.thresholds) === null || _column$thresholds === void 0 ? void 0 : _column$thresholds.length;
    })) === null || _card$content === void 0 ? void 0 : _card$content.map(function (column) {
      return column.dataSourceId;
    })) || [];

    // Consider existing thresholds outside columns and filter existing thresholds from edited column
    var allThresholds = isEmpty(columnThresholdDataSource) ? [] : (thresholds === null || thresholds === void 0 || (_thresholds$filter = thresholds.filter(function (_ref6) {
      var dataSourceId = _ref6.dataSourceId;
      return !columnThresholdDataSource.includes(dataSourceId);
    })) === null || _thresholds$filter === void 0 ? void 0 : _thresholds$filter.map(function (threshold) {
      return _objectSpread({}, threshold);
    })) || [];

    // the table card is looking for the thresholds on the main content object
    var updatedColumns = card === null || card === void 0 || (_card$content2 = card.content) === null || _card$content2 === void 0 || (_card$content2 = _card$content2.columns) === null || _card$content2 === void 0 ? void 0 : _card$content2.map(
    // eslint-disable-next-line no-unused-vars
    function (_ref7) {
      var columnThresholds = _ref7.thresholds,
        others = _objectWithoutProperties__default.default(_ref7, _excluded);
      if (!isEmpty(columnThresholds)) {
        allThresholds.push.apply(allThresholds, _toConsumableArray__default.default(columnThresholds.map(function (threshold) {
          return _objectSpread(_objectSpread({}, threshold), {}, {
            dataSourceId: others === null || others === void 0 ? void 0 : others.dataSourceId
          });
        })));
      }
      return others;
    });
    _onChange(_objectSpread(_objectSpread({}, card), {}, {
      content: _objectSpread(_objectSpread({}, omit(card.content, 'thresholds')), {}, {
        columns: updatedColumns
      }, !isEmpty(allThresholds) ? {
        thresholds: allThresholds
      } : {})
    }));
  }, [_onChange, thresholds]);
  var handleRemoveButton = React.useCallback(function (dataItem) {
    var _cardConfig$content2, _cardConfig$dataSourc3;
    var filteredColumns = dataSection.filter(function (item) {
      return item.dataSourceId !== dataItem.dataSourceId;
    });
    // Filter existing thresholds
    var filteredThresholds = cardConfig === null || cardConfig === void 0 || (_cardConfig$content2 = cardConfig.content) === null || _cardConfig$content2 === void 0 || (_cardConfig$content2 = _cardConfig$content2.thresholds) === null || _cardConfig$content2 === void 0 ? void 0 : _cardConfig$content2.filter(function (item) {
      return item.dataSourceId !== dataItem.dataSourceId;
    });
    // Need to determine whether we should remove these from the groupBy section
    var filteredGroupBy = cardConfig === null || cardConfig === void 0 || (_cardConfig$dataSourc3 = cardConfig.dataSource) === null || _cardConfig$dataSourc3 === void 0 || (_cardConfig$dataSourc3 = _cardConfig$dataSourc3.groupBy) === null || _cardConfig$dataSourc3 === void 0 ? void 0 : _cardConfig$dataSourc3.filter(function (groupByItem) {
      return groupByItem !== dataItem.dataSourceId;
    });
    setSelectedDataItems(filteredColumns.map(function (item) {
      return item.dataSourceId;
    }));

    // if we no longer have a groupBy, then we can exclude the dataSource from the response
    var updatedDataSource = {};
    if (!isEmpty(filteredGroupBy)) {
      updatedDataSource = {
        dataSource: _objectSpread(_objectSpread({}, cardConfig.dataSource), {}, {
          groupBy: filteredGroupBy
        })
      };
    } else if (cardConfig.dataSource) {
      updatedDataSource = {
        dataSource: _objectSpread({}, omit(cardConfig.dataSource, 'groupBy'))
      };
    }
    var updatedContent = _objectSpread(_objectSpread({}, cardConfig.content), {}, {
      columns: filteredColumns,
      thresholds: filteredThresholds
    });

    /* istanbul ignore else */
    if (isEmpty(filteredThresholds)) {
      delete updatedContent.thresholds;
    }
    _onChange(_objectSpread(_objectSpread({}, cardConfig), {}, {
      content: updatedContent
    }, updatedDataSource));
  }, [cardConfig, dataSection, _onChange, setSelectedDataItems]);
  var handleEditButton = React.useCallback(/*#__PURE__*/function () {
    var _ref8 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee(dataItem) {
      var dataItemWithMetaData, aggregationMethods;
      return _regeneratorRuntime__default.default.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            dataItemWithMetaData = validDataItems === null || validDataItems === void 0 ? void 0 : validDataItems.find(function (_ref9) {
              var dataItemId = _ref9.dataItemId;
              return dataItemId === dataItem.dataItemId;
            }); // Call back function for on click of edit button
            /* istanbul ignore else */
            if (!onEditDataItem) {
              _context.next = 6;
              break;
            }
            _context.next = 4;
            return onEditDataItem(cardConfig, dataItem, dataItemWithMetaData);
          case 4:
            aggregationMethods = _context.sent;
            if (dataItemWithMetaData && !isEmpty(aggregationMethods)) {
              dataItemWithMetaData.aggregationMethods = aggregationMethods;
            }
          case 6:
            // need to reset the card to include the latest dataSection
            setEditDataItem(_objectSpread(_objectSpread({}, dataItemWithMetaData), dataItem));
            setShowEditor(true);
          case 8:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x) {
      return _ref8.apply(this, arguments);
    };
  }(), [cardConfig, onEditDataItem, validDataItems]);
  var generateListItems = React.useCallback(function (data) {
    var _data$filter;
    var isHierarchy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return data === null || data === void 0 || (_data$filter = data.filter(function (dataItem) {
      return HierarchyDataFormItems.isHierarchyDataItem(dataItem) === isHierarchy;
    })) === null || _data$filter === void 0 ? void 0 : _data$filter.map(function (dataItem) {
      return {
        id: dataItem.dataSourceId,
        content: {
          value: dataItem.label || dataItem.dataItemId,
          icon: null,
          rowActions: function rowActions() {
            return [/*#__PURE__*/React__default.default.createElement(Button, {
              key: "data-item-".concat(dataItem.dataSourceId),
              renderIcon: iconsReact.Edit,
              hasIconOnly: true,
              kind: "ghost",
              size: "sm",
              onClick: function onClick() {
                return handleEditButton(dataItem);
              },
              iconDescription: mergedI18n.edit,
              tooltipPosition: "left",
              tooltipAlignment: "center"
            }), /*#__PURE__*/React__default.default.createElement(Button, {
              key: "data-item-".concat(dataItem.dataSourceId, "_remove"),
              renderIcon: iconsReact.MisuseOutline,
              hasIconOnly: true,
              kind: "ghost",
              size: "sm",
              onClick: function onClick() {
                return handleRemoveButton(dataItem);
              },
              iconDescription: mergedI18n.remove,
              tooltipPosition: "left",
              tooltipAlignment: "center"
            })];
          }
        }
      };
    });
  }, [handleEditButton, handleRemoveButton, mergedI18n.edit, mergedI18n.remove]);
  var dataListItems = React.useMemo(function () {
    return generateListItems(dataSection);
  }, [dataSection, generateListItems]);
  var hierarchyDataListItems = React.useMemo(function () {
    return generateListItems(dataSection, true);
  }, [dataSection, generateListItems]);
  return /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(iotPrefix, "--table-card-form--content")
  }, /*#__PURE__*/React__default.default.createElement(DataSeriesFormItemModal, {
    cardConfig: cardConfig,
    showEditor: showEditor,
    setShowEditor: setShowEditor,
    editDataSeries: dataSection,
    editDataItem: editDataItem,
    setEditDataItem: setEditDataItem,
    availableDimensions: availableDimensions,
    onChange: handleDataItemModalChanges,
    i18n: mergedI18n,
    actions: actions,
    options: {
      hasColorDropdown: false,
      hasUnit: false,
      hasDecimalPlacesDropdown: false,
      hasThresholds: true,
      hasTooltip: true
    },
    isLarge: true
  }), /*#__PURE__*/React__default.default.createElement(ContentFormItemTitle, {
    title: mergedI18n.tableColumnEditorSectionTitle,
    tooltip: _objectSpread({
      tooltipText: mergedI18n.dataItemEditorSectionTableTooltipText
    }, dataSeriesItemLinks !== null && dataSeriesItemLinks !== void 0 && dataSeriesItemLinks.table ? {
      linkText: mergedI18n.dataItemEditorSectionTooltipLinkText,
      href: dataSeriesItemLinks.table
    } : {})
  }), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input") // data item selector
  }, /*#__PURE__*/React__default.default.createElement(react.ComboBox
  // need to re-gen if selected card changes or if a dataItem is removed from the list
  , {
    key: "data-item-select-".concat(hash__default.default(validDataItems), "-selected_card-id-").concat(cardConfig.id),
    id: "".concat(cardConfig.id, "_dataSourceIds-combobox"),
    items: DataSeriesFormContent.formatDataItemsForDropdown(validDataItems),
    itemToString: function itemToString(item) {
      return item === null || item === void 0 ? void 0 : item.text;
    },
    titleText: mergedI18n.dataItem,
    addToList: false,
    placeholder: mergedI18n.filter,
    translateWithId: translateWithId,
    shouldFilterItem: function shouldFilterItem(_ref10) {
      var _item$text;
      var item = _ref10.item,
        inputValue = _ref10.inputValue;
      return isEmpty(inputValue) || (item === null || item === void 0 || (_item$text = item.text) === null || _item$text === void 0 || (_item$text = _item$text.toLowerCase()) === null || _item$text === void 0 ? void 0 : _item$text.includes(inputValue === null || inputValue === void 0 ? void 0 : inputValue.toLowerCase()));
    }
    // clears out the input field after each selection
    ,
    selectedItem: {
      id: '',
      text: ''
    },
    onChange: handleOnDataSeriesChange,
    light: true
  })), !isEmpty(validDimensions) && /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input") // Dimensions selector
  }, /*#__PURE__*/React__default.default.createElement(react.MultiSelect
  // need to re-gen if selected card changes or if a dataItem is removed from the list
  , {
    key: "data-item-select-selected_card-id-".concat(cardConfig.id),
    id: "".concat(cardConfig.id, "_dataSourceIds"),
    label: mergedI18n.selectGroupByDimensions,
    translateWithId: translateWithId,
    direction: "bottom",
    itemToString: function itemToString(item) {
      return item.id;
    },
    selectedItems: initialSelectedDimensions,
    items: validDimensions,
    light: true,
    onChange: function onChange(_ref11) {
      var selectedItems = _ref11.selectedItems;
      var existingDimensionColumns = dataSection.filter(editorUtils.dimensionFilterFunction);
      if (existingDimensionColumns.length > selectedItems.length) {
        var _existingDimensionCol;
        var selectedDimensions = selectedItems.map(function (dimension) {
          return dimension.text;
        });
        handleRemoveButton((_existingDimensionCol = existingDimensionColumns.find(function (dimension) {
          return !selectedDimensions.includes(dimension.dataSourceId);
        })) !== null && _existingDimensionCol !== void 0 ? _existingDimensionCol : {});
      } else {
        // Add the new dimensions as dimension columns at the beginning of the table
        var newCard = editorUtils.handleDataSeriesChange(selectedItems.map(function (i) {
          return {
            dataItemId: i.id,
            dataSourceId: i.id,
            label: i.text,
            dataItemType: 'DIMENSION',
            destination: 'groupBy'
          };
        }), cardConfig, null, null);
        _onChange(newCard);
      }
    },
    titleText: mergedI18n.dataItemEditorDimensionTitle
  })), /*#__PURE__*/React__default.default.createElement(List.default
  // Lists the selected dataItem columns in the bottom section and allow additional configuration
  , {
    key: "data-item-list".concat(selectedDataItems.length)
    // need to force an empty "empty state"
    ,
    emptyState: /*#__PURE__*/React__default.default.createElement("div", null),
    title: "",
    items: dataListItems
  }), /*#__PURE__*/React__default.default.createElement(HierarchyDataFormItems.default, {
    cardConfig: cardConfig,
    hierarchyDataItemListItems: hierarchyDataListItems,
    handleHierarchyDataItemChange: handleHierarchyDataItemChange,
    i18n: i18n,
    actions: actions
  }));
};
TableCardFormContent.defaultProps = defaultProps;
TableCardFormContent.propTypes = propTypes;
TableCardFormContent.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "TableCardFormContent",
  "props": {
    "cardConfig": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "id": {
            "name": "string",
            "required": false
          },
          "title": {
            "name": "string",
            "required": false
          },
          "size": {
            "name": "enum",
            "computed": true,
            "value": "Object.keys(CARD_SIZES)",
            "required": false
          },
          "type": {
            "name": "enum",
            "value": [{
              "value": "CARD_TYPES.TABLE",
              "computed": true
            }],
            "required": false
          },
          "content": {
            "name": "shape",
            "value": {
              "columns": {
                "name": "arrayOf",
                "value": {
                  "name": "shape",
                  "value": {
                    "label": {
                      "name": "string",
                      "required": false
                    },
                    "dataSourceId": {
                      "name": "string",
                      "required": false
                    },
                    "type": {
                      "name": "string",
                      "required": false
                    },
                    "dataItemType": {
                      "name": "string",
                      "required": false
                    }
                  }
                },
                "required": false
              },
              "thresholds": {
                "name": "arrayOf",
                "value": {
                  "name": "shape",
                  "value": {
                    "color": {
                      "name": "string",
                      "required": false
                    },
                    "comparison": {
                      "name": "string",
                      "required": false
                    },
                    "dataSourceId": {
                      "name": "string",
                      "required": false
                    },
                    "icon": {
                      "name": "string",
                      "required": false
                    },
                    "value": {
                      "name": "union",
                      "value": [{
                        "name": "number"
                      }, {
                        "name": "string"
                      }, {
                        "name": "bool"
                      }],
                      "required": false
                    }
                  }
                },
                "required": false
              }
            },
            "required": false
          },
          "dataSource": {
            "name": "shape",
            "value": {
              "groupBy": {
                "name": "arrayOf",
                "value": {
                  "name": "string"
                },
                "required": false
              }
            },
            "required": false
          }
        }
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  dataItemEditorTitle: 'Edit data series',\n  dataItemEditorDataItemTitle: 'Data item',\n  dataItemEditorDimensionTitle: 'Group by',\n  dataItemEditorDataItemLabel: 'Label',\n  dataItemEditorLegendColor: 'Legend color',\n  tableColumnEditorSectionTitle: 'Columns',\n  dataItemEditorSectionTableTooltipText:\n    'Display metrics in columns. Filter the metrics by dimensions or device ID from Group by.',\n  selectDataItems: 'Select data item(s)',\n  selectGroupByDimensions: 'Select dimension(s)',\n  dataItem: 'Data item',\n  edit: 'Edit',\n  remove: 'Remove',\n  filter: 'Filter',\n  customize: 'Customize',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "dataItemEditorTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDimensionTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemLabel": {
            "name": "string",
            "required": false
          },
          "dataItemEditorLegendColor": {
            "name": "string",
            "required": false
          },
          "tableColumnEditorSectionTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionTableTooltipText": {
            "name": "string",
            "required": false
          },
          "dataSeriesTitle": {
            "name": "string",
            "required": false
          },
          "selectDataItems": {
            "name": "string",
            "required": false
          },
          "selectGroupByDimensions": {
            "name": "string",
            "required": false
          },
          "dataItem": {
            "name": "string",
            "required": false
          },
          "edit": {
            "name": "string",
            "required": false
          },
          "remove": {
            "name": "string",
            "required": false
          },
          "customize": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "dataItems": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "an array of dataItems to be included on each card",
      "type": {
        "name": "custom",
        "raw": "DataItemsPropTypes"
      },
      "required": false
    },
    "getValidDataItems": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "if provided, returns an array of strings which are the dataItems to be allowed\non each card\ngetValidDataItems(card, selectedTimeRange)",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "selectedDataItems": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "list of dataItem names that have been selected to display on the card",
      "type": {
        "name": "arrayOf",
        "value": {
          "name": "string"
        }
      },
      "required": false
    },
    "availableDimensions": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "an object where the keys are available dimensions and the values are the values available for those dimensions\n ex: { manufacturer: ['Rentech', 'GHI Industries'], deviceid: ['73000', '73001', '73002'] }",
      "type": {
        "name": "shape",
        "value": {}
      },
      "required": false
    },
    "dataSeriesItemLinks": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "optional link href's for each card type that will appear in a tooltip",
      "type": {
        "name": "shape",
        "value": {
          "table": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "actions": {
      "defaultValue": {
        "value": "defaultDashboardEditorActionsProps",
        "computed": true
      },
      "description": "",
      "type": {
        "name": "custom",
        "raw": "DashboardEditorActionsPropTypes"
      },
      "required": false
    },
    "onChange": {
      "description": "",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "selectedTimeRange": {
      "description": "",
      "type": {
        "name": "string"
      },
      "required": true
    },
    "setSelectedDataItems": {
      "description": "the callback is called with a list of the new data item names selected",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "translateWithId": {
      "description": "",
      "type": {
        "name": "func"
      },
      "required": true
    }
  }
};
var TableCardFormContent$1 = TableCardFormContent;

module.exports = TableCardFormContent$1;
