'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isEmpty = require('../../../../../node_modules/lodash-es/isEmpty.js');
var omit = require('../../../../../node_modules/lodash-es/omit.js');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.array.map.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 LayoutConstants = require('../../../../../constants/LayoutConstants.js');
var ContentFormItemTitle = require('../ContentFormItemTitle.js');
var HierarchyDataFormItems = require('../HierarchyDataFormItems/HierarchyDataFormItems.js');
var cardUtilityFunctions = require('../../../../../utils/cardUtilityFunctions.js');
var BarChartDataSeriesContent = require('./BarChartDataSeriesContent.js');
var iconsReact = require('@carbon/icons-react');

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

var _asyncToGenerator__default = /*#__PURE__*/_interopDefault(_asyncToGenerator);
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);

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 = {
  /* card value */
  cardConfig: PropTypes__default.default.shape({
    id: PropTypes__default.default.string,
    title: PropTypes__default.default.string,
    size: PropTypes__default.default.string,
    type: PropTypes__default.default.string,
    content: PropTypes__default.default.oneOfType([PropTypes__default.default.shape({
      series: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
        label: PropTypes__default.default.string,
        dataSourceId: PropTypes__default.default.string,
        color: PropTypes__default.default.string
      })),
      xLabel: PropTypes__default.default.string,
      yLabel: PropTypes__default.default.string,
      unit: PropTypes__default.default.string,
      includeZeroOnXaxis: PropTypes__default.default.bool,
      includeZeroOnYaxis: PropTypes__default.default.bool,
      timeDataSourceId: PropTypes__default.default.string,
      showLegend: PropTypes__default.default.bool
    }),
    // custom card content is a function
    PropTypes__default.default.func]),
    interval: PropTypes__default.default.string
  }),
  /* callback when data item input value changes */
  onChange: PropTypes__default.default.func.isRequired,
  /** 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 array of dataItems to be included on each card
   * this prop will be ignored if getValidDataItems is defined
   */
  dataItems: editorUtils.DataItemsPropTypes,
  /** 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({}),
  /** list of dataItem names that have been selected to display on the card */
  selectedDataItems: PropTypes__default.default.arrayOf(PropTypes__default.default.string),
  setSelectedDataItems: PropTypes__default.default.func.isRequired,
  selectedTimeRange: PropTypes__default.default.string,
  isSummaryDashboard: PropTypes__default.default.bool,
  /** optional link href's for each card type that will appear in a tooltip */
  dataSeriesItemLinks: PropTypes__default.default.shape({
    simpleBar: PropTypes__default.default.string,
    groupedBar: PropTypes__default.default.string,
    stackedBar: PropTypes__default.default.string,
    timeSeries: PropTypes__default.default.string,
    value: PropTypes__default.default.string,
    custom: PropTypes__default.default.string
  }),
  i18n: PropTypes__default.default.shape({
    dataItemEditorTitle: PropTypes__default.default.string,
    dataItemEditorDataItemTitle: PropTypes__default.default.string,
    dataItemEditorDataItemLabel: PropTypes__default.default.string,
    dataItemEditorLegendColor: PropTypes__default.default.string,
    dataItemEditorSectionTitle: PropTypes__default.default.string,
    dataItemEditorSectionSimpleBarTooltipText: PropTypes__default.default.string,
    dataItemEditorSectionGroupedBarTooltipText: PropTypes__default.default.string,
    dataItemEditorSectionStackedBarTooltipText: PropTypes__default.default.string,
    dataItemEditorSectionTimeSeriesTooltipText: PropTypes__default.default.string,
    dataItemEditorSectionValueTooltipText: PropTypes__default.default.string,
    dataItemEditorSectionCustomTooltipText: PropTypes__default.default.string,
    dataItemEditorSectionTooltipLinkText: PropTypes__default.default.string,
    dataSeriesTitle: PropTypes__default.default.string,
    selectDataItems: PropTypes__default.default.string,
    selectDataItem: PropTypes__default.default.string,
    dataItem: PropTypes__default.default.string,
    edit: PropTypes__default.default.string,
    remove: PropTypes__default.default.string,
    customize: PropTypes__default.default.string,
    clearAllText: PropTypes__default.default.string,
    clearSelectionText: PropTypes__default.default.string,
    openMenuText: PropTypes__default.default.string,
    closeMenuText: PropTypes__default.default.string,
    incrementNumberText: PropTypes__default.default.string,
    decrementNumberText: PropTypes__default.default.string
  }),
  /** whether to use translated labels in cards */
  shouldUseTranslatedLabels: PropTypes__default.default.bool,
  translateWithId: PropTypes__default.default.func.isRequired,
  actions: editorUtils.DashboardEditorActionsPropTypes
};
var defaultProps = {
  cardConfig: {},
  selectedTimeRange: '',
  i18n: {
    dataItemEditorTitle: 'Edit data series',
    dataItemEditorDataItemTitle: 'Data item',
    dataItemEditorDataItemLabel: 'Label',
    dataItemEditorLegendColor: 'Legend color',
    dataItemEditorSectionTitle: 'Data',
    dataItemEditorSectionSimpleBarTooltipText: 'Display a metric using bars. Plot over time or by a dimension from Group by.',
    dataItemEditorSectionGroupedBarTooltipText: 'Group categories side by side in bars. Show groupings of related metrics or different categories of a single metric.',
    dataItemEditorSectionStackedBarTooltipText: 'Stack bars by categories of a single dimension or into multiple related metrics.',
    dataItemEditorSectionTimeSeriesTooltipText: 'Plot time series metrics over time.',
    dataItemEditorSectionValueTooltipText: 'Display metric values, dimension values, or alert counts. Select from Data item. ',
    dataItemEditorSectionCustomTooltipText: 'Show or hide alert fields. Choose dimensions to add as extra columns. ',
    dataItemEditorSectionTooltipLinkText: 'Learn more',
    selectDataItems: 'Select data items',
    selectDataItem: 'Select data item',
    dataItem: 'Data item',
    edit: 'Edit',
    remove: 'Remove',
    customize: 'Customize',
    filter: 'Filter',
    clearAllText: 'Clear all',
    clearSelectionText: 'Clear selection',
    openMenuText: 'Open menu',
    closeMenuText: 'Close menu',
    incrementNumberText: 'Increment number',
    decrementNumberText: 'Decrement number'
  },
  shouldUseTranslatedLabels: false,
  getValidDataItems: null,
  dataItems: [],
  selectedDataItems: [],
  availableDimensions: {},
  isSummaryDashboard: false,
  dataSeriesItemLinks: null,
  actions: editorUtils.defaultDashboardEditorActionsProps
};
var formatDataItemsForDropdown = function formatDataItemsForDropdown(dataItems) {
  return (dataItems === null || dataItems === void 0 ? void 0 : dataItems.map(function (_ref) {
    var dataItemId = _ref.dataItemId,
      label = _ref.label;
    return {
      id: dataItemId,
      text: label
    };
  })) || [];
};

/**
 * Retuns card specific tooltip depending on card type
 * @param {Object} cardConfig
 * @returns {Object} tooltip definition
 */
var defineCardSpecificTooltip = function defineCardSpecificTooltip(cardConfig, dataSeriesItemLinks, i18n) {
  switch (cardConfig.type) {
    case LayoutConstants.CARD_TYPES.BAR:
      if (cardConfig.content.type === LayoutConstants.BAR_CHART_TYPES.SIMPLE) {
        return _objectSpread({
          tooltipText: i18n.dataItemEditorSectionSimpleBarTooltipText
        }, dataSeriesItemLinks !== null && dataSeriesItemLinks !== void 0 && dataSeriesItemLinks.simpleBar ? {
          linkText: i18n.dataItemEditorSectionTooltipLinkText,
          href: dataSeriesItemLinks.simpleBar
        } : {});
      }
      if (cardConfig.content.type === LayoutConstants.BAR_CHART_TYPES.GROUPED) {
        return _objectSpread({
          tooltipText: i18n.dataItemEditorSectionGroupedBarTooltipText
        }, dataSeriesItemLinks !== null && dataSeriesItemLinks !== void 0 && dataSeriesItemLinks.groupedBar ? {
          linkText: i18n.dataItemEditorSectionTooltipLinkText,
          href: dataSeriesItemLinks.groupedBar
        } : {});
      }
      // STACKED
      return _objectSpread({
        tooltipText: i18n.dataItemEditorSectionStackedBarTooltipText
      }, dataSeriesItemLinks !== null && dataSeriesItemLinks !== void 0 && dataSeriesItemLinks.stackedBar ? {
        linkText: i18n.dataItemEditorSectionTooltipLinkText,
        href: dataSeriesItemLinks.stackedBar
      } : {});
    case LayoutConstants.CARD_TYPES.TIMESERIES:
      return _objectSpread({
        tooltipText: i18n.dataItemEditorSectionTimeSeriesTooltipText
      }, dataSeriesItemLinks !== null && dataSeriesItemLinks !== void 0 && dataSeriesItemLinks.timeSeries ? {
        linkText: i18n.dataItemEditorSectionTooltipLinkText,
        href: dataSeriesItemLinks.timeSeries
      } : {});
    case LayoutConstants.CARD_TYPES.VALUE:
      return _objectSpread({
        tooltipText: i18n.dataItemEditorSectionValueTooltipText
      }, dataSeriesItemLinks !== null && dataSeriesItemLinks !== void 0 && dataSeriesItemLinks.value ? {
        linkText: i18n.dataItemEditorSectionTooltipLinkText,
        href: dataSeriesItemLinks.value
      } : {});
    case LayoutConstants.CARD_TYPES.CUSTOM:
    default:
      return _objectSpread({
        tooltipText: i18n.dataItemEditorSectionCustomTooltipText
      }, dataSeriesItemLinks !== null && dataSeriesItemLinks !== void 0 && dataSeriesItemLinks.custom ? {
        linkText: i18n.dataItemEditorSectionTooltipLinkText,
        href: dataSeriesItemLinks.custom
      } : {});
  }
};
var baseClassName = "".concat(iotPrefix, "--card-edit-form");
var DataSeriesFormItem = function DataSeriesFormItem(_ref2) {
  var _cardConfig$content, _cardConfig$content2, _cardConfig$content3, _cardConfig$content4, _cardConfig$content5, _cardConfig$content6;
  var cardConfig = _ref2.cardConfig,
    isSummaryDashboard = _ref2.isSummaryDashboard,
    dataItems = _ref2.dataItems,
    getValidDataItems = _ref2.getValidDataItems,
    _onChange = _ref2.onChange,
    selectedDataItems = _ref2.selectedDataItems,
    setSelectedDataItems = _ref2.setSelectedDataItems,
    selectedTimeRange = _ref2.selectedTimeRange,
    availableDimensions = _ref2.availableDimensions,
    i18n = _ref2.i18n,
    shouldUseTranslatedLabels = _ref2.shouldUseTranslatedLabels,
    dataSeriesItemLinks = _ref2.dataSeriesItemLinks,
    translateWithId = _ref2.translateWithId,
    actions = _ref2.actions;
  var onEditDataItem = actions.onEditDataItem;
  var mergedI18n = React.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  var _useState = React.useState(false),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    showEditor = _useState2[0],
    setShowEditor = _useState2[1];
  var _useState3 = React.useState({}),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    editDataItem = _useState4[0],
    setEditDataItem = _useState4[1];
  var _useState5 = React.useState(((_cardConfig$content = cardConfig.content) === null || _cardConfig$content === void 0 ? void 0 : _cardConfig$content.series) || []),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    editDataSeries = _useState6[0],
    setEditDataSeries = _useState6[1];
  var _useState7 = React.useState([]),
    _useState8 = _slicedToArray__default.default(_useState7, 2),
    removedDataItems = _useState8[0],
    setRemovedDataItems = _useState8[1];
  var canMultiSelectDataItems = ((_cardConfig$content2 = cardConfig.content) === null || _cardConfig$content2 === void 0 ? void 0 : _cardConfig$content2.type) !== LayoutConstants.BAR_CHART_TYPES.SIMPLE;
  var type = cardConfig.type;

  // determine which content section to look at
  var dataSection = cardConfig.type === LayoutConstants.CARD_TYPES.TIMESERIES || cardConfig.type === LayoutConstants.CARD_TYPES.BAR ? cardConfig === null || cardConfig === void 0 || (_cardConfig$content3 = cardConfig.content) === null || _cardConfig$content3 === void 0 ? void 0 : _cardConfig$content3.series : cardConfig === null || cardConfig === void 0 || (_cardConfig$content4 = cardConfig.content) === null || _cardConfig$content4 === void 0 ? void 0 : _cardConfig$content4.attributes;
  var removedItemsCountRef = React.useRef(0);
  var validDataItems = React.useMemo(function () {
    return getValidDataItems ? getValidDataItems(cardConfig, selectedTimeRange) : dataItems;
  }, [cardConfig, dataItems, getValidDataItems, selectedTimeRange]);
  var cardSpecificTooltip = defineCardSpecificTooltip(cardConfig, dataSeriesItemLinks, mergedI18n);
  var handleSimpleDataSeriesChange = React.useCallback(function (_ref3) {
    var selectedItem = _ref3.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 (_ref4) {
        var dataItemId = _ref4.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 attributes
        // if it's going into the groupBy section then just use the dataItem ID
        dataSourceId: (itemWithMetaData === null || itemWithMetaData === void 0 ? void 0 : itemWithMetaData.destination) === 'groupBy' ? selectedItem.id : "".concat(selectedItem.id, "_").concat(uuid.v4())
      })]);
      // need to remove the category if the card is a stacked timeseries bar
      var card = cardConfig.content.type === LayoutConstants.BAR_CHART_TYPES.STACKED && cardConfig.content.timeDataSourceId && selectedItems.length > 1 ? omit(cardConfig, 'content.categoryDataSourceId') : cardConfig;
      var newCard = editorUtils.handleDataSeriesChange(selectedItems, card, setEditDataSeries, undefined, removedItemsCountRef);
      setSelectedDataItems(selectedItems.map(function (_ref5) {
        var dataSourceId = _ref5.dataSourceId;
        return dataSourceId;
      }));
      _onChange(newCard);
    }
  }, [cardConfig, dataSection, _onChange, setSelectedDataItems, validDataItems]);
  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 = canMultiSelectDataItems ? [].concat(_toConsumableArray__default.default(dataSection), _toConsumableArray__default.default(updatedItems)) : [updatedItems[0]];
    var newCard = editorUtils.handleDataSeriesChange(selectedItems, cardConfig, setEditDataSeries, undefined, removedItemsCountRef);
    setSelectedDataItems(selectedItems.map(function (_ref6) {
      var dataSourceId = _ref6.dataSourceId;
      return dataSourceId;
    }));
    _onChange(newCard);
  }, [canMultiSelectDataItems, cardConfig, dataSection, _onChange, setSelectedDataItems]);
  var handleEditButton = React.useCallback(/*#__PURE__*/function () {
    var _ref7 = _asyncToGenerator__default.default(/*#__PURE__*/_regeneratorRuntime__default.default.mark(function _callee(dataItem, i) {
      var dataItemWithMetaData, colorIndex, 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 (_ref8) {
              var dataItemId = _ref8.dataItemId;
              return dataItemId === dataItem.dataItemId;
            });
            colorIndex = (removedItemsCountRef.current + i) % editorUtils.DATAITEM_COLORS_OPTIONS.length; // Call back function for on click of edit button
            if (!onEditDataItem) {
              _context.next = 7;
              break;
            }
            _context.next = 5;
            return onEditDataItem(cardConfig, dataItem, dataItemWithMetaData);
          case 5:
            aggregationMethods = _context.sent;
            if (!isEmpty(aggregationMethods)) {
              dataItemWithMetaData.aggregationMethods = aggregationMethods;
            }
          case 7:
            // need to reset the card to include the latest dataSection
            _onChange(_objectSpread(_objectSpread({}, cardConfig), {}, {
              content: _objectSpread(_objectSpread({}, cardConfig.content), cardConfig.type === LayoutConstants.CARD_TYPES.VALUE ? {
                attributes: dataSection
              } : {
                series: dataSection
              })
            }));
            setEditDataItem(_objectSpread(_objectSpread(_objectSpread({}, dataItemWithMetaData), dataItem), cardConfig.type === LayoutConstants.CARD_TYPES.TIMESERIES || cardConfig.type === LayoutConstants.CARD_TYPES.BAR ? {
              color: dataItem.color || editorUtils.DATAITEM_COLORS_OPTIONS[colorIndex]
            } : {}));
            setShowEditor(true);
          case 10:
          case "end":
            return _context.stop();
        }
      }, _callee);
    }));
    return function (_x, _x2) {
      return _ref7.apply(this, arguments);
    };
  }(), [cardConfig, dataSection, _onChange, onEditDataItem, validDataItems]);
  var handleRemoveButton = React.useCallback(function (dataItem) {
    var filteredItems = dataSection.filter(function (item) {
      return item.dataSourceId !== dataItem.dataSourceId;
    });
    removedItemsCountRef.current += 1;
    setSelectedDataItems(filteredItems.map(function (item) {
      return item.dataSourceId;
    }));
    setRemovedDataItems([].concat(_toConsumableArray__default.default(removedDataItems), [dataItem]));
    setEditDataSeries(filteredItems);
    _onChange(_objectSpread(_objectSpread({}, cardConfig), {}, {
      content: _objectSpread(_objectSpread({}, cardConfig.content), cardConfig.type === LayoutConstants.CARD_TYPES.VALUE ? {
        attributes: filteredItems
      } : {
        series: filteredItems
      })
    }));
  }, [cardConfig, dataSection, _onChange, removedDataItems, setSelectedDataItems]);
  var generateListItems = React.useCallback(function (data) {
    var isHierarchy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    return (data === null || data === void 0 ? void 0 : data.filter(function (dataItem) {
      return HierarchyDataFormItems.isHierarchyDataItem(dataItem) === isHierarchy;
    }).map(function (dataItem, i) {
      var colorIndex = (i + removedItemsCountRef.current) % editorUtils.DATAITEM_COLORS_OPTIONS.length;
      var iconColorOption = dataItem.color || editorUtils.DATAITEM_COLORS_OPTIONS[colorIndex];
      return {
        id: dataItem.dataSourceId,
        content: {
          value: cardUtilityFunctions.getTranslatedLabel(dataItem.label || dataItem.dataItemId, shouldUseTranslatedLabels, i18n),
          icon: cardConfig.type === LayoutConstants.CARD_TYPES.TIMESERIES || cardConfig.type === LayoutConstants.CARD_TYPES.BAR ? /*#__PURE__*/React__default.default.createElement("div", {
            className: "".concat(baseClassName, "--data-item-list--item-color-icon"),
            style: {
              '--icon-color-option': iconColorOption
            }
          }) : null,
          rowActions: function rowActions() {
            return [/*#__PURE__*/React__default.default.createElement(Button, {
              key: "data-item-".concat(dataItem.dataSourceId, "_edit"),
              renderIcon: iconsReact.Edit,
              hasIconOnly: true,
              kind: "ghost",
              size: "sm",
              onClick: function onClick() {
                return handleEditButton(dataItem, i);
              },
              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"
            })];
          }
        }
      };
    })) || [];
  }, [cardConfig.type, handleEditButton, handleRemoveButton, i18n, mergedI18n.edit, mergedI18n.remove, shouldUseTranslatedLabels]);
  var dataItemListItems = React.useMemo(function () {
    return generateListItems(dataSection);
  }, [dataSection, generateListItems]);
  var hierarchyDataItemListItems = React.useMemo(function () {
    return generateListItems(dataSection, true);
  }, [dataSection, generateListItems]);
  return /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(DataSeriesFormItemModal, {
    cardConfig: cardConfig,
    isSummaryDashboard: isSummaryDashboard,
    showEditor: showEditor,
    setShowEditor: setShowEditor,
    editDataSeries: editDataSeries,
    setEditDataSeries: setEditDataSeries,
    editDataItem: editDataItem,
    setEditDataItem: setEditDataItem,
    validDataItems: validDataItems,
    availableDimensions: availableDimensions,
    dataSection: dataSection,
    onChange: _onChange,
    i18n: mergedI18n,
    shouldUseTranslatedLabels: shouldUseTranslatedLabels,
    actions: actions,
    options: {
      hasColorDropdown: type === LayoutConstants.CARD_TYPES.TIMESERIES || type === LayoutConstants.CARD_TYPES.BAR,
      hasUnit: type === LayoutConstants.CARD_TYPES.VALUE,
      hasDecimalPlacesDropdown: type === LayoutConstants.CARD_TYPES.VALUE,
      hasThresholds: type === LayoutConstants.CARD_TYPES.VALUE,
      hasTooltip: type === LayoutConstants.CARD_TYPES.VALUE
    },
    isLarge: true
  }), !isEmpty(validDataItems) && /*#__PURE__*/React__default.default.createElement(React__default.default.Fragment, null, /*#__PURE__*/React__default.default.createElement(ContentFormItemTitle, {
    title: mergedI18n.dataItemEditorSectionTitle
    // Specific to each card type
    ,
    tooltip: _objectSpread({}, cardSpecificTooltip)
  }), cardConfig.type === LayoutConstants.CARD_TYPES.BAR && /*#__PURE__*/React__default.default.createElement(BarChartDataSeriesContent, {
    cardConfig: cardConfig,
    onChange: _onChange,
    availableDimensions: availableDimensions,
    i18n: mergedI18n,
    translateWithId: translateWithId
  }), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(baseClassName, "--input")
  }, canMultiSelectDataItems ? /*#__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),
    "data-testid": "editor--data-series--combobox",
    id: "".concat(cardConfig.id, "_dataSourceIds-combobox"),
    items: formatDataItemsForDropdown(validDataItems),
    itemToString: function itemToString(item) {
      return item === null || item === void 0 ? void 0 : item.text;
    },
    titleText: mergedI18n.dataItemEditorDataItemTitle,
    addToList: false,
    translateWithId: translateWithId,
    shouldFilterItem: function shouldFilterItem(_ref9) {
      var _item$text;
      var item = _ref9.item,
        inputValue = _ref9.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()));
    },
    placeholder: mergedI18n.filter
    // clears out the input field after each selection
    ,
    selectedItem: {
      id: '',
      text: ''
    },
    onChange: handleSimpleDataSeriesChange,
    light: true
  }) :
  /*#__PURE__*/
  // Can't select more than one dataItem
  React__default.default.createElement(react.Dropdown, {
    id: "".concat(cardConfig.id, "_dataSourceId"),
    direction: "bottom",
    label: mergedI18n.selectDataItem,
    light: true,
    translateWithId: translateWithId,
    title: mergedI18n.selectDataItem,
    titleText: mergedI18n.dataItem,
    items: validDataItems.map(function (_ref10) {
      var dataSourceId = _ref10.dataSourceId;
      return dataSourceId;
    }),
    selectedItem: !isEmpty(dataItemListItems) && !isEmpty((_cardConfig$content5 = cardConfig.content) === null || _cardConfig$content5 === void 0 ? void 0 : _cardConfig$content5.series) ? (_cardConfig$content6 = cardConfig.content) === null || _cardConfig$content6 === void 0 ? void 0 : _cardConfig$content6.series[0].dataItemId : null,
    onChange: function onChange(_ref11) {
      var selectedItem = _ref11.selectedItem;
      var itemWithMetaData = validDataItems === null || validDataItems === void 0 ? void 0 : validDataItems.find(function (_ref12) {
        var dataSourceId = _ref12.dataSourceId;
        return dataSourceId === selectedItem;
      });
      var newCard = editorUtils.handleDataSeriesChange([_objectSpread(_objectSpread({
        id: selectedItem
      }, itemWithMetaData && _objectSpread({}, itemWithMetaData)), {}, {
        dataSourceId: "".concat(selectedItem, "_").concat(uuid.v4())
      })], cardConfig, setEditDataSeries);
      setSelectedDataItems([selectedItem]);
      _onChange(newCard);
    }
  })), /*#__PURE__*/React__default.default.createElement(List.default, {
    className: "".concat(baseClassName, "--data-item-list"),
    key: "data-item-list".concat(selectedDataItems.length)
    // need to force an empty "empty state"
    ,
    emptyState: /*#__PURE__*/React__default.default.createElement("div", null),
    title: "",
    items: dataItemListItems
  })), /*#__PURE__*/React__default.default.createElement(HierarchyDataFormItems.default, {
    listClassName: "".concat(baseClassName, "--data-item-list"),
    cardConfig: cardConfig,
    hierarchyDataItemListItems: hierarchyDataItemListItems,
    handleHierarchyDataItemChange: handleHierarchyDataItemChange,
    i18n: i18n,
    actions: actions
  }));
};
DataSeriesFormItem.defaultProps = defaultProps;
DataSeriesFormItem.propTypes = propTypes;
DataSeriesFormItem.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "DataSeriesFormItem",
  "props": {
    "cardConfig": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "id": {
            "name": "string",
            "required": false
          },
          "title": {
            "name": "string",
            "required": false
          },
          "size": {
            "name": "string",
            "required": false
          },
          "type": {
            "name": "string",
            "required": false
          },
          "content": {
            "name": "union",
            "value": [{
              "name": "shape",
              "value": {
                "series": {
                  "name": "arrayOf",
                  "value": {
                    "name": "shape",
                    "value": {
                      "label": {
                        "name": "string",
                        "required": false
                      },
                      "dataSourceId": {
                        "name": "string",
                        "required": false
                      },
                      "color": {
                        "name": "string",
                        "required": false
                      }
                    }
                  },
                  "required": false
                },
                "xLabel": {
                  "name": "string",
                  "required": false
                },
                "yLabel": {
                  "name": "string",
                  "required": false
                },
                "unit": {
                  "name": "string",
                  "required": false
                },
                "includeZeroOnXaxis": {
                  "name": "bool",
                  "required": false
                },
                "includeZeroOnYaxis": {
                  "name": "bool",
                  "required": false
                },
                "timeDataSourceId": {
                  "name": "string",
                  "required": false
                },
                "showLegend": {
                  "name": "bool",
                  "required": false
                }
              }
            }, {
              "name": "func"
            }],
            "required": false
          },
          "interval": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "selectedTimeRange": {
      "defaultValue": {
        "value": "''",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{\n  dataItemEditorTitle: 'Edit data series',\n  dataItemEditorDataItemTitle: 'Data item',\n  dataItemEditorDataItemLabel: 'Label',\n  dataItemEditorLegendColor: 'Legend color',\n  dataItemEditorSectionTitle: 'Data',\n  dataItemEditorSectionSimpleBarTooltipText:\n    'Display a metric using bars. Plot over time or by a dimension from Group by.',\n  dataItemEditorSectionGroupedBarTooltipText:\n    'Group categories side by side in bars. Show groupings of related metrics or different categories of a single metric.',\n  dataItemEditorSectionStackedBarTooltipText:\n    'Stack bars by categories of a single dimension or into multiple related metrics.',\n  dataItemEditorSectionTimeSeriesTooltipText: 'Plot time series metrics over time.',\n  dataItemEditorSectionValueTooltipText:\n    'Display metric values, dimension values, or alert counts. Select from Data item. ',\n  dataItemEditorSectionCustomTooltipText:\n    'Show or hide alert fields. Choose dimensions to add as extra columns. ',\n  dataItemEditorSectionTooltipLinkText: 'Learn more',\n  selectDataItems: 'Select data items',\n  selectDataItem: 'Select data item',\n  dataItem: 'Data item',\n  edit: 'Edit',\n  remove: 'Remove',\n  customize: 'Customize',\n  filter: 'Filter',\n  clearAllText: 'Clear all',\n  clearSelectionText: 'Clear selection',\n  openMenuText: 'Open menu',\n  closeMenuText: 'Close menu',\n  incrementNumberText: 'Increment number',\n  decrementNumberText: 'Decrement number',\n}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "dataItemEditorTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorDataItemLabel": {
            "name": "string",
            "required": false
          },
          "dataItemEditorLegendColor": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionTitle": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionSimpleBarTooltipText": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionGroupedBarTooltipText": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionStackedBarTooltipText": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionTimeSeriesTooltipText": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionValueTooltipText": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionCustomTooltipText": {
            "name": "string",
            "required": false
          },
          "dataItemEditorSectionTooltipLinkText": {
            "name": "string",
            "required": false
          },
          "dataSeriesTitle": {
            "name": "string",
            "required": false
          },
          "selectDataItems": {
            "name": "string",
            "required": false
          },
          "selectDataItem": {
            "name": "string",
            "required": false
          },
          "dataItem": {
            "name": "string",
            "required": false
          },
          "edit": {
            "name": "string",
            "required": false
          },
          "remove": {
            "name": "string",
            "required": false
          },
          "customize": {
            "name": "string",
            "required": false
          },
          "clearAllText": {
            "name": "string",
            "required": false
          },
          "clearSelectionText": {
            "name": "string",
            "required": false
          },
          "openMenuText": {
            "name": "string",
            "required": false
          },
          "closeMenuText": {
            "name": "string",
            "required": false
          },
          "incrementNumberText": {
            "name": "string",
            "required": false
          },
          "decrementNumberText": {
            "name": "string",
            "required": false
          }
        }
      },
      "required": false
    },
    "shouldUseTranslatedLabels": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "whether to use translated labels in cards",
      "type": {
        "name": "bool"
      },
      "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
    },
    "dataItems": {
      "defaultValue": {
        "value": "[]",
        "computed": false
      },
      "description": "an array of dataItems to be included on each card\nthis prop will be ignored if getValidDataItems is defined",
      "type": {
        "name": "custom",
        "raw": "DataItemsPropTypes"
      },
      "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
    },
    "isSummaryDashboard": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "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": {
          "simpleBar": {
            "name": "string",
            "required": false
          },
          "groupedBar": {
            "name": "string",
            "required": false
          },
          "stackedBar": {
            "name": "string",
            "required": false
          },
          "timeSeries": {
            "name": "string",
            "required": false
          },
          "value": {
            "name": "string",
            "required": false
          },
          "custom": {
            "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
    },
    "setSelectedDataItems": {
      "description": "",
      "type": {
        "name": "func"
      },
      "required": true
    },
    "translateWithId": {
      "description": "",
      "type": {
        "name": "func"
      },
      "required": true
    }
  }
};
var DataSeriesFormContent = DataSeriesFormItem;

exports.default = DataSeriesFormContent;
exports.defineCardSpecificTooltip = defineCardSpecificTooltip;
exports.formatDataItemsForDropdown = formatDataItemsForDropdown;
