import _extends from '@babel/runtime/helpers/extends';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import isEmpty from '../../node_modules/lodash-es/isEmpty.js';
import uniqBy from '../../node_modules/lodash-es/uniqBy.js';
import isNil from '../../node_modules/lodash-es/isNil.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.fill.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.find.js';
import 'core-js/modules/es.array.find-index.js';
import 'core-js/modules/es.array.includes.js';
import 'core-js/modules/es.array.map.js';
import 'core-js/modules/es.function.name.js';
import 'core-js/modules/es.object.get-own-property-descriptor.js';
import 'core-js/modules/es.object.get-own-property-descriptors.js';
import 'core-js/modules/es.object.keys.js';
import 'core-js/modules/es.object.to-string.js';
import 'core-js/modules/es.string.includes.js';
import 'core-js/modules/web.dom-collections.for-each.js';
import React__default from 'react';
import PropTypes from 'prop-types';
import { v4 } from 'uuid';
import { purple70, cyan50, teal70, magenta70, red50, red90, green60, blue80, magenta50, purple50, teal50, cyan90, red60, green50, orange40, yellow30, blue60 } from '@carbon/colors';
import { DASHBOARD_EDITOR_CARD_TYPES, CARD_SIZES, CARD_TYPES, BAR_CHART_TYPES, BAR_CHART_LAYOUTS } from '../../constants/LayoutConstants.js';
import { User, Location, Temperature, Flag, Tag, Alarm, Checkmark, CheckmarkFilled, CheckmarkOutline, Error, ErrorFilled, ErrorOutline, Help, HelpFilled, Information, InformationFilled, Misuse, MisuseOutline, Undefined, UndefinedFilled, Unknown, UnknownFilled, Warning, WarningAlt, WarningAltFilled, WarningAltInverted, WarningAltInvertedFilled, WarningFilled, WarningSquare, WarningSquareFilled } from '@carbon/icons-react';

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var validHotspotIcons = [{
  id: 'User',
  icon: User,
  text: 'User'
}, {
  id: 'Location',
  icon: Location,
  text: 'Location'
}, {
  id: 'Temperature',
  icon: Temperature,
  text: 'Temperature'
}, {
  id: 'Flag',
  icon: Flag,
  text: 'Flag'
}, {
  id: 'Tag',
  icon: Tag,
  text: 'Tag'
}, {
  id: 'Alarm',
  icon: Alarm,
  text: 'Alarm'
}];
var DataItemsPropTypes = PropTypes.arrayOf(PropTypes.shape({
  /** This is needed to keep track of the original dataItem name
   * because the dataSourceId is subject to change */
  dataItemId: PropTypes.string.isRequired,
  dataSourceId: PropTypes.string.isRequired,
  /** Maps to data item columnType */
  type: PropTypes.string,
  /** Maps to data item type */
  dataItemType: PropTypes.string,
  label: PropTypes.string,
  aggregationMethod: PropTypes.string,
  aggregationMethods: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.string,
    text: PropTypes.string
  })),
  /** Grain is needed in summary dashboard editors */
  grain: PropTypes.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: 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(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, DASHBOARD_EDITOR_CARD_TYPES.VALUE, CARD_SIZES.SMALL), DASHBOARD_EDITOR_CARD_TYPES.SIMPLE_BAR, CARD_SIZES.MEDIUM), DASHBOARD_EDITOR_CARD_TYPES.GROUPED_BAR, CARD_SIZES.MEDIUM), DASHBOARD_EDITOR_CARD_TYPES.STACKED_BAR, CARD_SIZES.MEDIUM), DASHBOARD_EDITOR_CARD_TYPES.TIMESERIES, CARD_SIZES.MEDIUM), DASHBOARD_EDITOR_CARD_TYPES.IMAGE, CARD_SIZES.MEDIUM), DASHBOARD_EDITOR_CARD_TYPES.TABLE, CARD_SIZES.LARGE);
  var baseCardProps = _objectSpread({
    id: v4(),
    title: i18n.defaultCardTitle,
    size: (_defaultSizeForType$t = defaultSizeForType[type]) !== null && _defaultSizeForType$t !== void 0 ? _defaultSizeForType$t : CARD_SIZES.MEDIUM
  }, type.includes(CARD_TYPES.BAR) ? {
    type: CARD_TYPES.BAR
  } : {
    type: type
  });
  switch (type) {
    case DASHBOARD_EDITOR_CARD_TYPES.VALUE:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          attributes: []
        }
      });
    case DASHBOARD_EDITOR_CARD_TYPES.TIMESERIES:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          series: [],
          xLabel: 'Time',
          includeZeroOnXaxis: false,
          includeZeroOnYaxis: false,
          timeDataSourceId: 'timestamp',
          showLegend: true
        }
      });
    case DASHBOARD_EDITOR_CARD_TYPES.SIMPLE_BAR:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          type: BAR_CHART_TYPES.SIMPLE,
          layout: BAR_CHART_LAYOUTS.VERTICAL,
          series: [],
          timeDataSourceId: 'timestamp'
        }
      });
    case DASHBOARD_EDITOR_CARD_TYPES.GROUPED_BAR:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          type: BAR_CHART_TYPES.GROUPED,
          layout: BAR_CHART_LAYOUTS.VERTICAL,
          series: [],
          categoryDataSourceId: i18n.selectAGroupBy
        }
      });
    case DASHBOARD_EDITOR_CARD_TYPES.STACKED_BAR:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          type: BAR_CHART_TYPES.STACKED,
          layout: BAR_CHART_LAYOUTS.VERTICAL,
          series: [],
          timeDataSourceId: 'timestamp'
        }
      });
    case DASHBOARD_EDITOR_CARD_TYPES.TABLE:
      return _objectSpread(_objectSpread({}, baseCardProps), {}, {
        content: {
          columns: [],
          allowNavigation: true,
          showHeader: true
        }
      });
    case 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 = [purple70, cyan50, teal70, magenta70, red50, red90, green60, blue80, magenta50, purple50, teal50, 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.createElement(Checkmark, {
    size: 24
  }),
  name: 'Checkmark'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(CheckmarkFilled, {
    size: 24
  }),
  name: 'Checkmark filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(CheckmarkOutline, {
    size: 24
  }),
  name: 'Checkmark outline'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(Error, {
    size: 24
  }),
  name: 'Error'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(ErrorFilled, {
    size: 24
  }),
  name: 'Error filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(ErrorOutline, {
    size: 24
  }),
  name: 'Error outline'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(Help, {
    size: 24
  }),
  name: 'Help'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(HelpFilled, {
    size: 24
  }),
  name: 'Help filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(Information, {
    size: 24
  }),
  name: 'Information'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(InformationFilled, {
    size: 24
  }),
  name: 'Information filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(Misuse, {
    size: 24
  }),
  name: 'Misuse'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(MisuseOutline, {
    size: 24
  }),
  name: 'Misuse outline'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(Undefined, {
    size: 24
  }),
  name: 'Undefined'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(UndefinedFilled, {
    size: 24
  }),
  name: 'Undefined filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(Unknown, {
    size: 24
  }),
  name: 'Unknown'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(UnknownFilled, {
    size: 24
  }),
  name: 'Unknown filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(Warning, {
    size: 24
  }),
  name: 'Warning'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(WarningAlt, {
    size: 24
  }),
  name: 'Warning alt'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(WarningAltFilled, {
    size: 24
  }),
  name: 'Warning alt filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(WarningAltInverted, {
    size: 24
  }),
  name: 'Warning alt inverted'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(WarningAltInvertedFilled, {
    size: 24
  }),
  name: 'Warning alt inverted filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(WarningFilled, {
    size: 24
  }),
  name: 'Warning filled'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(WarningSquare, {
    size: 24
  }),
  name: 'Warning square'
}, {
  carbonIcon: /*#__PURE__*/React__default.createElement(WarningSquareFilled, {
    size: 24
  }),
  name: 'Warning square filled'
}];
var validThresholdColors = [{
  carbonColor: red60,
  name: 'red60'
}, {
  carbonColor: green50,
  name: 'green50'
}, {
  carbonColor: orange40,
  name: 'orange40'
}, {
  carbonColor: yellow30,
  name: 'yellow30'
}, {
  carbonColor: 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 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 CARD_TYPES.TIMESERIES:
      return !isNil(cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.content);
    case CARD_TYPES.BAR:
      return !isNil(cardConfig === null || cardConfig === void 0 ? void 0 : cardConfig.content);
    case 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 CARD_TYPES.VALUE:
      attributes = formatAttributes(selectedItems, cardConfig);
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          attributes: attributes
        })
      });
    case CARD_TYPES.TIMESERIES:
    case CARD_TYPES.BAR:
      series = formatSeries(selectedItems, cardConfig, removedItemsCountRef);
      setEditDataSeries(series);
      return _objectSpread(_objectSpread({}, cardConfig), {}, {
        content: _objectSpread(_objectSpread({}, cardConfig.content), {}, {
          series: series
        })
      });
    case 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(allDimensionColumns), _toConsumableArray(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 CARD_TYPES.IMAGE:
      {
        var _cardConfig$content4;
        var dataSection = _toConsumableArray(((_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 CARD_TYPES.VALUE:
      dataSection = _toConsumableArray(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 CARD_TYPES.TIMESERIES:
    case CARD_TYPES.BAR:
      dataSection = _toConsumableArray(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 CARD_TYPES.TABLE:
      dataSection = _toConsumableArray(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 CARD_TYPES.IMAGE:
      dataSection = _toConsumableArray(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.createElement(matchingHotspotIcon.icon, _objectSpread(_objectSpread({}, iconProps), {}, {
    title: matchingHotspotIcon.text
  }))) : matchingThresholdIcon ? (/*#__PURE__*/React__default.cloneElement(matchingThresholdIcon.carbonIcon, _objectSpread(_objectSpread({}, iconProps), {}, {
    title: matchingThresholdIcon.name
  }))) : /*#__PURE__*/React__default.createElement(Warning, _extends({
    size: 24
  }, iconProps));

  // otherwise default to Warning24
  // eslint-disable-next-line react/prop-types
  return /*#__PURE__*/React__default.createElement("div", {
    style: {
      color: iconProps.fill
    }
  }, iconToRender);
};
var DashboardEditorActionsPropTypes = PropTypes.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.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.func,
  /** Form actions for dataSeries modal */
  dataSeriesFormActions: PropTypes.shape({
    /** callback function to determine aggregation dropdown visibility
     * hasAggregationsDropDown(editDataItem: selected dataSource)
     * return {boolean} : true or false
     */
    hasAggregationsDropDown: PropTypes.func,
    /** callback function to determine grain dropdown visibility
     * hasGrainsDropDown(cardProps: card properties, editDataItem: selected dataSource)
     * return {boolean} : true or false
     */
    hasGrainsDropDown: PropTypes.func,
    /** callback function to determine dataFilter dropdown visibility
     * hasDataFilterDropdown(cardProps: card properties)
     * return {boolean} : true or false
     */
    hasDataFilterDropdown: PropTypes.func,
    /** callback function to determine hierarchyDataItems dropdown visibility
     * hasHierarchyDataItemsEnabled(cardProps: card properties)
     * return {boolean} : true or false
     */
    hasHierarchyDataItemsEnabled: PropTypes.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"
};

export { DATAITEM_COLORS_OPTIONS, DashboardEditorActionsPropTypes, DataItemsPropTypes, defaultDashboardEditorActionsProps, dimensionFilterFunction, formatAttributes, formatSeries, getDefaultCard, getDuplicateCard, handleDataSeriesChange, handleDefaultDataItemEdit, handleKeyDown, handleOnClick, isCardJsonValid, renderBreakpointInfo, renderDefaultIconByName, timeRangeToJSON, validHotspotIcons, validThresholdColors, validThresholdIcons };
