'use strict';

var _extends = require('@babel/runtime/helpers/extends');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isEmpty = require('../../node_modules/lodash-es/isEmpty.js');
var uniqBy = require('../../node_modules/lodash-es/uniqBy.js');
var isNil = require('../../node_modules/lodash-es/isNil.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.array.fill.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.array.map.js');
require('core-js/modules/es.function.name.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 colors = require('@carbon/colors');
var LayoutConstants = require('../../constants/LayoutConstants.js');
var iconsReact = require('@carbon/icons-react');

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

var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _toConsumableArray__default = /*#__PURE__*/_interopDefault(_toConsumableArray);
var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);

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 validHotspotIcons = [{
  id: 'User',
  icon: iconsReact.User,
  text: 'User'
}, {
  id: 'Location',
  icon: iconsReact.Location,
  text: 'Location'
}, {
  id: 'Temperature',
  icon: iconsReact.Temperature,
  text: 'Temperature'
}, {
  id: 'Flag',
  icon: iconsReact.Flag,
  text: 'Flag'
}, {
  id: 'Tag',
  icon: iconsReact.Tag,
  text: 'Tag'
}, {
  id: 'Alarm',
  icon: iconsReact.Alarm,
  text: 'Alarm'
}];
var DataItemsPropTypes = PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
  /** This is needed to keep track of the original dataItem name
   * because the dataSourceId is subject to change */
  dataItemId: PropTypes__default.default.string.isRequired,
  dataSourceId: PropTypes__default.default.string.isRequired,
  /** Maps to data item columnType */
  type: PropTypes__default.default.string,
  /** Maps to data item type */
  dataItemType: PropTypes__default.default.string,
  label: PropTypes__default.default.string,
  aggregationMethod: PropTypes__default.default.string,
  aggregationMethods: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
    id: PropTypes__default.default.string,
    text: PropTypes__default.default.string
  })),
  /** Grain is needed in summary dashboard editors */
  grain: PropTypes__default.default.string
}));

/**
 * Returns a duplicate card configuration
 * @param {Object} cardConfig, card JSON configuration
 * @returns {Object} duplicated card JSON
 */
var getDuplicateCard = function getDuplicateCard(cardConfig) {
  return _objectSpread(_objectSpread({}, cardConfig), {}, {
    id: uuid.v4()
  });
};

/**
 * Returns a default card configuration
 * @param {string} type, card type
 * @returns {Object} default card JSON
 */
var getDefaultCard = function getDefaultCard(type, i18n) {
  var _defaultSizeForType$t;
  var defaultSizeForType = _defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default(_defineProperty__default.default({}, LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.VALUE, LayoutConstants.CARD_SIZES.SMALL), LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.SIMPLE_BAR, LayoutConstants.CARD_SIZES.MEDIUM), LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.GROUPED_BAR, LayoutConstants.CARD_SIZES.MEDIUM), LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.STACKED_BAR, LayoutConstants.CARD_SIZES.MEDIUM), LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.TIMESERIES, LayoutConstants.CARD_SIZES.MEDIUM), LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.IMAGE, LayoutConstants.CARD_SIZES.MEDIUM), LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.TABLE, LayoutConstants.CARD_SIZES.LARGE);
  var baseCardProps = _objectSpread({
    id: uuid.v4(),
    title: i18n.defaultCardTitle,
    size: (_defaultSizeForType$t = defaultSizeForType[type]) !== null && _defaultSizeForType$t !== void 0 ? _defaultSizeForType$t : LayoutConstants.CARD_SIZES.MEDIUM
  }, type.includes(LayoutConstants.CARD_TYPES.BAR) ? {
    type: LayoutConstants.CARD_TYPES.BAR
  } : {
    type: type
  });
  switch (type) {
    case LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.VALUE:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          attributes: []
        }
      });
    case LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.TIMESERIES:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          series: [],
          xLabel: 'Time',
          includeZeroOnXaxis: false,
          includeZeroOnYaxis: false,
          timeDataSourceId: 'timestamp',
          showLegend: true
        }
      });
    case LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.SIMPLE_BAR:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          type: LayoutConstants.BAR_CHART_TYPES.SIMPLE,
          layout: LayoutConstants.BAR_CHART_LAYOUTS.VERTICAL,
          series: [],
          timeDataSourceId: 'timestamp'
        }
      });
    case LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.GROUPED_BAR:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          type: LayoutConstants.BAR_CHART_TYPES.GROUPED,
          layout: LayoutConstants.BAR_CHART_LAYOUTS.VERTICAL,
          series: [],
          categoryDataSourceId: i18n.selectAGroupBy
        }
      });
    case LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.STACKED_BAR:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          type: LayoutConstants.BAR_CHART_TYPES.STACKED,
          layout: LayoutConstants.BAR_CHART_LAYOUTS.VERTICAL,
          series: [],
          timeDataSourceId: 'timestamp'
        }
      });
    case LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.TABLE:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          columns: [],
          allowNavigation: true,
          showHeader: true
        }
      });
    case LayoutConstants.DASHBOARD_EDITOR_CARD_TYPES.IMAGE:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          hideMinimap: true,
          hideHotspots: false,
          hideZoomControls: false,
          displayOption: 'contain'
        }
      });
    default:
      return _objectSpread({}, baseCardProps);
  }
};

/**
 * Color options for dataItems
 */
var DATAITEM_COLORS_OPTIONS = [colors.purple70, colors.cyan50, colors.teal70, colors.magenta70, colors.red50, colors.red90, colors.green60, colors.blue80, colors.magenta50, colors.purple50, colors.teal50, colors.cyan90];

/**
 * maps a selected time range to what is expected in the dashboardJSON
 */
var timeRangeToJSON = {
  lastHour: {
    interval: 'hour',
    range: {
      interval: 'hour',
      count: -1,
      type: 'rolling'
    }
  },
  last2Hours: {
    interval: 'hour',
    range: {
      interval: 'hour',
      count: -2,
      type: 'rolling'
    }
  },
  last4Hours: {
    interval: 'hour',
    range: {
      interval: 'hour',
      count: -4,
      type: 'rolling'
    }
  },
  last8Hours: {
    interval: 'hour',
    range: {
      interval: 'hour',
      count: -8,
      type: 'rolling'
    }
  },
  last24Hours: {
    range: {
      interval: 'day',
      count: -1,
      type: 'rolling'
    },
    interval: 'hour'
  },
  last7Days: {
    range: {
      interval: 'week',
      count: -1,
      type: 'rolling'
    },
    interval: 'day'
  },
  lastMonth: {
    range: {
      interval: 'month',
      count: -1,
      type: 'rolling'
    },
    interval: 'week'
  },
  lastQuarter: {
    range: {
      interval: 'quarter',
      count: -1,
      type: 'rolling'
    },
    interval: 'month'
  },
  lastYear: {
    range: {
      interval: 'year',
      count: -1,
      type: 'rolling'
    },
    interval: 'month'
  },
  thisWeek: {
    range: {
      interval: 'week',
      count: -1,
      type: 'periodToDate'
    },
    interval: 'day'
  },
  thisMonth: {
    range: {
      interval: 'month',
      count: -1,
      type: 'periodToDate'
    },
    interval: 'week'
  },
  thisQuarter: {
    range: {
      interval: 'quarter',
      count: -1,
      type: 'periodToDate'
    },
    interval: 'month'
  },
  thisYear: {
    range: {
      interval: 'year',
      count: -1,
      type: 'periodToDate'
    },
    interval: 'month'
  }
};
var validThresholdIcons = [{
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Checkmark, {
    size: 24
  }),
  name: 'Checkmark'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.CheckmarkFilled, {
    size: 24
  }),
  name: 'Checkmark filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.CheckmarkOutline, {
    size: 24
  }),
  name: 'Checkmark outline'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Error, {
    size: 24
  }),
  name: 'Error'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.ErrorFilled, {
    size: 24
  }),
  name: 'Error filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.ErrorOutline, {
    size: 24
  }),
  name: 'Error outline'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Help, {
    size: 24
  }),
  name: 'Help'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.HelpFilled, {
    size: 24
  }),
  name: 'Help filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Information, {
    size: 24
  }),
  name: 'Information'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.InformationFilled, {
    size: 24
  }),
  name: 'Information filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Misuse, {
    size: 24
  }),
  name: 'Misuse'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.MisuseOutline, {
    size: 24
  }),
  name: 'Misuse outline'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Undefined, {
    size: 24
  }),
  name: 'Undefined'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.UndefinedFilled, {
    size: 24
  }),
  name: 'Undefined filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Unknown, {
    size: 24
  }),
  name: 'Unknown'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.UnknownFilled, {
    size: 24
  }),
  name: 'Unknown filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.Warning, {
    size: 24
  }),
  name: 'Warning'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.WarningAlt, {
    size: 24
  }),
  name: 'Warning alt'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.WarningAltFilled, {
    size: 24
  }),
  name: 'Warning alt filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.WarningAltInverted, {
    size: 24
  }),
  name: 'Warning alt inverted'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.WarningAltInvertedFilled, {
    size: 24
  }),
  name: 'Warning alt inverted filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.WarningFilled, {
    size: 24
  }),
  name: 'Warning filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.WarningSquare, {
    size: 24
  }),
  name: 'Warning square'
}, {
  carbonIcon: /*#__PURE__*/React__default.default.createElement(iconsReact.WarningSquareFilled, {
    size: 24
  }),
  name: 'Warning square filled'
}];
var validThresholdColors = [{
  carbonColor: colors.red60,
  name: 'red60'
}, {
  carbonColor: colors.green50,
  name: 'green50'
}, {
  carbonColor: colors.orange40,
  name: 'orange40'
}, {
  carbonColor: colors.yellow30,
  name: 'yellow30'
}, {
  carbonColor: colors.blue60,
  name: 'blue60'
}];

/**
 * determines if a card JSON is valid depending on its card type
 * @param {Object} cardConfig
 * @returns {Boolean}
 */
var isCardJsonValid = function isCardJsonValid(cardConfig) {
  var _cardConfig$content;
  switch (cardConfig.type) {
    case LayoutConstants.CARD_TYPES.VALUE:
      return !isNil(cardConfig === null || cardConfig === void 0 || (_cardConfig$content = cardConfig.content) === null || _cardConfig$content === void 0 ? void 0 : _cardConfig$content.attributes);
    case LayoutConstants.CARD_TYPES.TIMESERIES:
      return !isNil(cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.content);
    case LayoutConstants.CARD_TYPES.BAR:
      return !isNil(cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.content);
    case LayoutConstants.CARD_TYPES.TABLE:
      return !isNil(cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.content);
    default:
      return true;
  }
};

/**
 * Selects the card if the key is 'enter' or 'space'
 * @param {Event} evt
 * @param {Function} onSelectCard
 * @param {string} id
 */
var handleKeyDown = function handleKeyDown(evt, onSelectCard, id) {
  if (evt.key === 'Enter' || evt.key === 'Space') {
    onSelectCard(id);
  }
};

/**
 * Selects the card
 * @param {Function} onSelectCard
 * @param {string} id
 */
var handleOnClick = function handleOnClick(onSelectCard, id) {
  onSelectCard(id);
};

/**
 * Returns the correct string based off the currently selected breakpoint
 * @param {string} breakpoint One of the breakpoints we support with DashboardGrid
 * @param {Object<string>} i18n internationalization strings
 * @returns {string} translated info about the selected breakpoint
 */
var renderBreakpointInfo = function renderBreakpointInfo(breakpoint, i18n) {
  switch (breakpoint) {
    case 'lg':
      return i18n.layoutInfoLg;
    case 'md':
      return i18n.layoutInfoMd;
    case 'sm':
      return i18n.layoutInfoSm;
    default:
      return i18n.layoutInfoLg;
  }
};

/**
 * returns a new series array with a generated color if needed, and in the format expected by the JSON payload
 * @param {array} selectedItems
 * @param {object} cardConfig
 * @param {ref} removedItemsCountRef ref to keep track of the number of items removed to keep the colors different and prevent collisions
 */
var formatSeries = function formatSeries(selectedItems, cardConfig) {
  var _cardConfig$content2;
  var removedItemsCountRef = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
    current: 0
  };
  var cardSeries = cardConfig === null || cardConfig === void 0 || (_cardConfig$content2 = cardConfig.content) === null || _cardConfig$content2 === void 0 ? void 0 : _cardConfig$content2.series;
  var series = selectedItems.map(function (selectedItem, i) {
    var _currentItem$color;
    var unEditedLabel = selectedItem.label,
      dataSourceId = selectedItem.dataSourceId;
    var colorIndex = (removedItemsCountRef.current + i) % DATAITEM_COLORS_OPTIONS.length;
    var currentItem = cardSeries === null || cardSeries === void 0 ? void 0 : cardSeries.find(function (dataItem) {
      return dataItem.dataSourceId === dataSourceId;
    });
    var color = (_currentItem$color = currentItem === null || currentItem === void 0 ? void 0 : currentItem.color) !== null && _currentItem$color !== void 0 ? _currentItem$color : DATAITEM_COLORS_OPTIONS[colorIndex];
    var label = (currentItem === null || currentItem === void 0 ? void 0 : currentItem.label) || unEditedLabel || dataSourceId;
    return _objectSpread(_objectSpread(_objectSpread({}, currentItem), selectedItem), {}, {
      label: label,
      color: color
    });
  });
  return series;
};

/**
 * returns a new attributes array in the format expected by the JSON payload
 * @param {array} selectedItems
 * @param {object} cardConfig
 */
var formatAttributes = function formatAttributes(selectedItems, cardConfig) {
  var _cardConfig$content3;
  var currentCardAttributes = cardConfig === null || cardConfig === void 0 || (_cardConfig$content3 = cardConfig.content) === null || _cardConfig$content3 === void 0 ? void 0 : _cardConfig$content3.attributes;
  var attributes = selectedItems.map(function (selectedItem) {
    var unEditedLabel = selectedItem.label,
      dataSourceId = selectedItem.dataSourceId;
    var currentItem = currentCardAttributes === null || currentCardAttributes === void 0 ? void 0 : currentCardAttributes.find(function (dataItem) {
      return dataItem.dataSourceId === dataSourceId;
    });
    // Need to default the label to reflect the default aggregator if there isn't one set
    var label = (currentItem === null || currentItem === void 0 ? void 0 : currentItem.label) || unEditedLabel || dataSourceId;
    return _objectSpread(_objectSpread(_objectSpread({}, currentItem), selectedItem), {}, {
      label: label
    });
  });
  return attributes;
};
var dimensionFilterFunction = function dimensionFilterFunction(col) {
  return col.dataItemType === 'DIMENSION' || col.destination === 'groupBy' && col.dataSourceId === 'deviceid';
}; // For manually added deviceId dimension

/**
 * determines how to format the dataSection based on card type
 * @param {array} selectedItems
 * @param {object} cardConfig
 * @param {function} setEditDataSeries
 * @param {number} hotspotIndex
 * @param {ref} removedItemsCountRef ref to keep track of the number of items removed from the card to keep track of colors and prevent collisions
 */
var handleDataSeriesChange = function handleDataSeriesChange(selectedItems, cardConfig, setEditDataSeries, hotspotIndex) {
  var removedItemsCountRef = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
    current: 0
  };
  var type = cardConfig.type,
    content = cardConfig.content;
  var series;
  var attributes;
  switch (type) {
    case LayoutConstants.CARD_TYPES.VALUE:
      attributes = formatAttributes(selectedItems, cardConfig);
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          attributes: attributes
        })
      });
    case LayoutConstants.CARD_TYPES.TIMESERIES:
    case LayoutConstants.CARD_TYPES.BAR:
      series = formatSeries(selectedItems, cardConfig, removedItemsCountRef);
      setEditDataSeries(series);
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          series: series
        })
      });
    case LayoutConstants.CARD_TYPES.TABLE:
      {
        var columns = Array.isArray(content === null || content === void 0 ? void 0 : content.columns) ? content.columns : [];

        // in certain cases (for groupBy updates) the full set of attribute columns isn't passed
        var existingAttributeColumns = columns.filter(function (col) {
          return col.dataItemType !== 'DIMENSION' && col.dataSourceId !== 'timestamp';
        });

        // find the new attributes to add because we're adding dimensions later
        var attributeColumns = selectedItems.filter(function (dataItem) {
          return dataItem.dataItemType !== 'DIMENSION';
        });

        // start off with a default timestamp column if we don't already have one
        var timestampColumn = columns.find(function (col) {
          return col.dataSourceId === 'timestamp';
        }) || {
          dataSourceId: 'timestamp',
          dataItemId: 'timestamp',
          label: 'Timestamp',
          type: 'TIMESTAMP',
          columnType: 'TIMESTAMP',
          sort: 'DESC'
        };
        var existingDimensionColumns = columns.filter(dimensionFilterFunction);

        // new dimension columns should go right after the timestamp column
        var dimensionColumns = selectedItems.filter(dimensionFilterFunction);
        var allDimensionColumns = existingDimensionColumns.concat(dimensionColumns);

        // for raw table cards, the dimensions columns go in the attributes section
        // if groupBy was selected, the dimension columns should go in the groupBy section
        var updatedGroupBy = uniqBy(allDimensionColumns, 'dataSourceId').filter(function (item) {
          return item.destination === 'groupBy';
        }).map(function (item) {
          return item.dataItemId || item.dataSourceId;
        });
        return _objectSpread(_objectSpread({}, cardConfig), {}, {
          content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
            columns: uniqBy([timestampColumn].concat(_toConsumableArray__default.default(allDimensionColumns), _toConsumableArray__default.default(existingAttributeColumns.concat(attributeColumns))), 'dataSourceId') // when columns are removed, their dataSourceId is cleared, we don't want to readd them
            .filter(function (column) {
              return column.dataSourceId;
            })
          })
        }, !isEmpty(updatedGroupBy) ? {
          dataSource: _objectSpread(_objectSpread({}, cardConfig.dataSource), allDimensionColumns.find(function (item) {
            return item.destination === 'groupBy';
          }) ? {
            groupBy: updatedGroupBy
          } : {})
        } : {});
      }
    case LayoutConstants.CARD_TYPES.IMAGE:
      {
        var _cardConfig$content4;
        var dataSection = _toConsumableArray__default.default(((_cardConfig$content4 = cardConfig.content) === null || _cardConfig$content4 === void 0 ? void 0 : _cardConfig$content4.hotspots) || []);
        dataSection[hotspotIndex].content = _objectSpread(_objectSpread({}, dataSection[hotspotIndex].content), {}, {
          attributes: selectedItems
        });
        return _objectSpread(_objectSpread({}, cardConfig), {}, {
          content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
            hotspots: dataSection
          })
        });
      }
    default:
      return cardConfig;
  }
};

/**
 * updates the dataSection on edit of a dataItem based on card type.
 * TODO: refactor this into multiple functions
 * @param {object} editDataItem an object with the updated form values for this data item
 * @param {object} cardConfig the previous cardConfiguration
 * @param {string} editDataSeries only used for bar chart card forms
 * @param {int} hotspotIndex which of the hotspots in the content section should be updated (only used for image card updates)
 */
var handleDefaultDataItemEdit = function handleDefaultDataItemEdit(editDataItem, cardConfig, editDataSeries, hotspotIndex) {
  var type = cardConfig.type,
    content = cardConfig.content;
  var dataSection;
  var editDataItemIndex;
  switch (type) {
    case LayoutConstants.CARD_TYPES.VALUE:
      dataSection = _toConsumableArray__default.default(content.attributes);
      editDataItemIndex = dataSection.findIndex(function (dataItem) {
        return dataItem.dataSourceId === editDataItem.dataSourceId || dataItem.dataItemId === editDataItem.dataItemId && dataItem.label === editDataItem.label;
      });
      // if there isn't an item found, place it at the end
      dataSection[editDataItemIndex !== -1 ? editDataItemIndex : dataSection.length] = editDataItem;
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, content), {}, {
          attributes: dataSection
        })
      });
    case LayoutConstants.CARD_TYPES.TIMESERIES:
    case LayoutConstants.CARD_TYPES.BAR:
      dataSection = _toConsumableArray__default.default(content.series);
      editDataItemIndex = dataSection.findIndex(function (dataItem) {
        return dataItem.dataSourceId === editDataItem.dataSourceId || dataItem.dataItemId === editDataItem.dataItemId && dataItem.label === editDataItem.label;
      });
      // if there isn't an item found, place it at the end
      dataSection[editDataItemIndex !== -1 ? editDataItemIndex : dataSection.length] = editDataItem;
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, content), {}, {
          series: dataSection
        })
      });
    case LayoutConstants.CARD_TYPES.TABLE:
      dataSection = _toConsumableArray__default.default(content.columns);
      editDataItemIndex = dataSection.findIndex(function (dataItem) {
        return dataItem.dataSourceId === editDataItem.dataSourceId;
      });
      dataSection[editDataItemIndex] = editDataItem;
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          columns: dataSection
        })
      });
    case LayoutConstants.CARD_TYPES.IMAGE:
      dataSection = _toConsumableArray__default.default(content.hotspots || []);
      if (dataSection.length) {
        editDataItemIndex = dataSection[hotspotIndex].content.attributes.findIndex(function (dataItem) {
          return dataItem.dataSourceId === editDataItem.dataSourceId;
        });
        dataSection[hotspotIndex].content.attributes[editDataItemIndex] = editDataItem;
      }
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, content), {}, {
          hotspots: dataSection
        })
      });
    default:
      return cardConfig;
  }
};
var renderDefaultIconByName = function renderDefaultIconByName(iconName) {
  var iconProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  // first search the validHotspot Icons
  var matchingHotspotIcon = validHotspotIcons.find(function (icon) {
    return icon.id === iconName;
  });

  // then search the validThresholdIcons
  var matchingThresholdIcon = validThresholdIcons.find(function (icon) {
    return icon.name === iconName;
  });
  var iconToRender = matchingHotspotIcon ? (/*#__PURE__*/React__default.default.createElement(matchingHotspotIcon.icon, _objectSpread(_objectSpread({}, iconProps), {}, {
    title: matchingHotspotIcon.text
  }))) : matchingThresholdIcon ? (/*#__PURE__*/React__default.default.cloneElement(matchingThresholdIcon.carbonIcon, _objectSpread(_objectSpread({}, iconProps), {}, {
    title: matchingThresholdIcon.name
  }))) : /*#__PURE__*/React__default.default.createElement(iconsReact.Warning, _extends__default.default({
    size: 24
  }, iconProps));

  // otherwise default to Warning24
  // eslint-disable-next-line react/prop-types
  return /*#__PURE__*/React__default.default.createElement("div", {
    style: {
      color: iconProps.fill
    }
  }, iconToRender);
};
var DashboardEditorActionsPropTypes = PropTypes__default.default.shape({
  /** Call back function for on click of edit button, returns aggregationMethods for a selcted dataSource
   * onEditDataItem(cardConfig: card properties, dataItem: selected dataItem, dataItemWithMetaData: selected dataItem with meta data);
   * return {object}: returns aggregationMethods for a selcted dataSource
   * ex:
   *[
      {
          "id": "none",
          "text": "None"
      },
      {
          "id": "mean",
          "text": "Mean",
      },
      {
          "id": "min",
          "text": "Minimum",
      }
    ]
   */
  onEditDataItem: PropTypes__default.default.func,
  /** Call back function for on click of add hierarchy data items button, returns a selcted dataSource
   * onAddHierarchyDataItems(cardProps: card properties, handleHierarchyDataItemChange: callback function to handle hierarchy data items change)
   * return: void
   */
  onAddHierarchyDataItems: PropTypes__default.default.func,
  /** Form actions for dataSeries modal */
  dataSeriesFormActions: PropTypes__default.default.shape({
    /** callback function to determine aggregation dropdown visibility
     * hasAggregationsDropDown(editDataItem: selected dataSource)
     * return {boolean} : true or false
     */
    hasAggregationsDropDown: PropTypes__default.default.func,
    /** callback function to determine grain dropdown visibility
     * hasGrainsDropDown(cardProps: card properties, editDataItem: selected dataSource)
     * return {boolean} : true or false
     */
    hasGrainsDropDown: PropTypes__default.default.func,
    /** callback function to determine dataFilter dropdown visibility
     * hasDataFilterDropdown(cardProps: card properties)
     * return {boolean} : true or false
     */
    hasDataFilterDropdown: PropTypes__default.default.func,
    /** callback function to determine hierarchyDataItems dropdown visibility
     * hasHierarchyDataItemsEnabled(cardProps: card properties)
     * return {boolean} : true or false
     */
    hasHierarchyDataItemsEnabled: PropTypes__default.default.func
  })
});

/* istanbul ignore next */
var noop = function noop() {};
var defaultDashboardEditorActionsProps = {
  onEditDataItem: noop,
  onAddHierarchyDataItems: noop,
  dataSeriesFormActions: {
    hasAggregationsDropDown: noop,
    hasGrainsDropDown: noop,
    hasDataFilterDropdown: noop,
    hasHierarchyDataItemsEnabled: noop
  }
};
renderDefaultIconByName.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "renderDefaultIconByName"
};

exports.DATAITEM_COLORS_OPTIONS = DATAITEM_COLORS_OPTIONS;
exports.DashboardEditorActionsPropTypes = DashboardEditorActionsPropTypes;
exports.DataItemsPropTypes = DataItemsPropTypes;
exports.defaultDashboardEditorActionsProps = defaultDashboardEditorActionsProps;
exports.dimensionFilterFunction = dimensionFilterFunction;
exports.formatAttributes = formatAttributes;
exports.formatSeries = formatSeries;
exports.getDefaultCard = getDefaultCard;
exports.getDuplicateCard = getDuplicateCard;
exports.handleDataSeriesChange = handleDataSeriesChange;
exports.handleDefaultDataItemEdit = handleDefaultDataItemEdit;
exports.handleKeyDown = handleKeyDown;
exports.handleOnClick = handleOnClick;
exports.isCardJsonValid = isCardJsonValid;
exports.renderBreakpointInfo = renderBreakpointInfo;
exports.renderDefaultIconByName = renderDefaultIconByName;
exports.timeRangeToJSON = timeRangeToJSON;
exports.validHotspotIcons = validHotspotIcons;
exports.validThresholdColors = validThresholdColors;
exports.validThresholdIcons = validThresholdIcons;
