import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _extends from '@babel/runtime/helpers/extends';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import isNil from '../../node_modules/lodash-es/isNil.js';
import isEqual from '../../node_modules/lodash-es/isEqual.js';
import _omit from '../../node_modules/lodash-es/omit.js';
import 'core-js/modules/es.symbol.js';
import 'core-js/modules/es.symbol.description.js';
import 'core-js/modules/es.array.concat.js';
import 'core-js/modules/es.array.filter.js';
import 'core-js/modules/es.array.find.js';
import 'core-js/modules/es.array.iterator.js';
import 'core-js/modules/es.array.map.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/web.dom-collections.for-each.js';
import 'core-js/modules/web.dom-collections.iterator.js';
import React__default, { useState, useEffect, useCallback, useMemo } from 'react';
import update from 'immutability-helper';
import { usePrevious } from '../../hooks/usePrevious.js';
import { CARD_ACTIONS, CARD_TYPES } from '../../constants/LayoutConstants.js';
import { handleKeyDown, handleOnClick } from './editorUtils.js';
import DashboardEditorDefaultCardRenderer from './DashboardEditorDefaultCardRenderer.js';

var _excluded = ["style", "children"],
  _excluded2 = ["isSelected", "availableDimensions", "i18n", "onRemove", "onDuplicate", "onCardChange", "setSelectedCardId", "renderIconByName", "onShowImageGallery", "onValidateUploadedImage", "baseClassName", "renderCardPreview", "style", "shouldUseTranslatedLabels"];
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; }

/**
 *
 * This component is needed to cache the style object for performance reasons because unfortunately, the style object changes with every render from React Grid Layout
 */
var CachedEditorCardRenderer = function CachedEditorCardRenderer(_ref) {
  var style = _ref.style,
    children = _ref.children,
    others = _objectWithoutProperties(_ref, _excluded);
  var _useState = useState(style),
    _useState2 = _slicedToArray(_useState, 2),
    cachedStyle = _useState2[0],
    setCachedStyle = _useState2[1];
  var _useState3 = useState(children),
    _useState4 = _slicedToArray(_useState3, 2),
    cachedChildren = _useState4[0],
    setCachedChildren = _useState4[1];
  var previousStyle = usePrevious(style);

  // Unfortunately the react-grid-layout creates a new style object every render
  useEffect(function () {
    if (!isEqual(style, previousStyle)) {
      setCachedStyle(style);
    }
  }, [previousStyle, style]);

  // Unfortunately the react-grid keeps putting a new child object every render, only need to refresh if it's resizable
  useEffect(function () {
    setCachedChildren(children);
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [others.isResizable]);
  return /*#__PURE__*/React__default.createElement(DashboardEditorCardRenderer, _extends({}, others, {
    style: cachedStyle
  }), cachedChildren // this is a performance enhancement because the children were always being recreated
  );
};
CachedEditorCardRenderer.defaultProps = {
  style: {}
};
var shouldComponentSkipUpdate = function shouldComponentSkipUpdate(prevProps, nextProps) {
  return isEqual(prevProps, nextProps);
};
var availableActions = {
  clone: true,
  delete: true
};
/**
 * Returns a Card component for preview in the dashboard.  Decides whether to call the renderCardPreview function or use our default renderer.
 * Also handles converting the low level card callback events into the higher level ones
 * @param {Object} availableDimensions collection of dimensions where the key is the
 * dimension and the value is a list of values for that dimension
 * @returns {Node}
 */
var DashboardEditorCardRenderer = /*#__PURE__*/React__default.memo(function (_ref2) {
  var _cardProps$values2;
  var isSelected = _ref2.isSelected,
    availableDimensions = _ref2.availableDimensions,
    i18n = _ref2.i18n,
    onRemove = _ref2.onRemove,
    onDuplicate = _ref2.onDuplicate,
    onCardChange = _ref2.onCardChange,
    setSelectedCardId = _ref2.setSelectedCardId,
    renderIconByName = _ref2.renderIconByName,
    onShowImageGallery = _ref2.onShowImageGallery,
    onValidateUploadedImage = _ref2.onValidateUploadedImage,
    baseClassName = _ref2.baseClassName,
    renderCardPreview = _ref2.renderCardPreview,
    style = _ref2.style,
    shouldUseTranslatedLabels = _ref2.shouldUseTranslatedLabels,
    cardConfig = _objectWithoutProperties(_ref2, _excluded2);
  // We have to keep track of our dynamic hotspots here
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    dynamicHotspots = _useState6[0],
    setDynamicHotspots = _useState6[1];
  var handleOnCardAction = useCallback(function (id, actionId, payload) {
    if (actionId === CARD_ACTIONS.CLONE_CARD) {
      onDuplicate(id);
    } else if (actionId === CARD_ACTIONS.DELETE_CARD) {
      onRemove(id);
    } else if (actionId === CARD_ACTIONS.ON_CARD_CHANGE) {
      onCardChange(update(cardConfig, payload));
    }
  }, [cardConfig, onCardChange, onDuplicate, onRemove]);
  var handleOnCardKeyDown = useCallback(function (e) {
    handleKeyDown(e, setSelectedCardId, cardConfig);
  }, [cardConfig, setSelectedCardId]);
  var handleOnCardMouseDown = useCallback(function (e) {
    handleOnClick(setSelectedCardId, cardConfig);
    cardConfig.onMouseDown(e);
  },
  // Need to disable the eslint role because I don't want to regen if any other part of cardConfig changes
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [cardConfig, cardConfig.onMouseDown, setSelectedCardId]);
  // Need to memoize these card props at this level to improve performance
  var cardProps = useMemo(function () {
    var _cardConfig$content;
    return _objectSpread(_objectSpread({}, cardConfig), {}, {
      style: style,
      key: cardConfig.id,
      tooltip: cardConfig.description,
      i18n: i18n,
      shouldUseTranslatedLabels: shouldUseTranslatedLabels,
      availableActions: availableActions,
      onCardAction: handleOnCardAction,
      renderIconByName: renderIconByName,
      tabIndex: 0,
      onKeyDown: handleOnCardKeyDown,
      onMouseDown: handleOnCardMouseDown,
      className: "".concat(baseClassName, "--preview__card"),
      isSelected: isSelected,
      // Add the show gallery to image card
      onBrowseClick: cardConfig.type === CARD_TYPES.IMAGE && isNil((_cardConfig$content = cardConfig.content) === null || _cardConfig$content === void 0 ? void 0 : _cardConfig$content.src) ? onShowImageGallery : undefined,
      validateUploadedImage: cardConfig.type === CARD_TYPES.IMAGE ? onValidateUploadedImage : undefined
    });
  }, [baseClassName, cardConfig, handleOnCardAction, handleOnCardKeyDown, handleOnCardMouseDown, i18n, isSelected, onShowImageGallery, onValidateUploadedImage, renderIconByName, shouldUseTranslatedLabels, style]);
  useEffect(function () {
    var _cardProps$values;
    var originalDynamicHotspot = (_cardProps$values = cardProps.values) === null || _cardProps$values === void 0 || (_cardProps$values = _cardProps$values.hotspots) === null || _cardProps$values === void 0 ? void 0 : _cardProps$values.find(function (hotspot) {
      return hotspot.type === 'dynamic';
    });
    // if we have dynamic hotspots and a way to fetch them, fetch them
    if (originalDynamicHotspot && cardProps.onFetchDynamicDemoHotspots) {
      cardProps.onFetchDynamicDemoHotspots().then(function (hotspots) {
        return setDynamicHotspots(hotspots.map(function (hotspot) {
          return _objectSpread(_objectSpread({}, hotspot), _omit(originalDynamicHotspot, 'type', 'x', 'y'));
        }));
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [(_cardProps$values2 = cardProps.values) === null || _cardProps$values2 === void 0 || (_cardProps$values2 = _cardProps$values2.hotspots) === null || _cardProps$values2 === void 0 ? void 0 : _cardProps$values2.length, cardProps.onFetchDynamicDemoHotspots]);

  // If the renderCardPreview function returns a valid value for the card, use it,
  if (typeof renderCardPreview === 'function' && renderCardPreview(cardConfig, cardProps, setSelectedCardId, onDuplicate, onRemove, isSelected, onShowImageGallery, availableDimensions)) {
    return renderCardPreview(cardConfig, cardProps, setSelectedCardId, onDuplicate, onRemove, isSelected, onShowImageGallery, availableDimensions);
  }

  // otherwise use our default renderers
  // If it's an image card we need to update its dynamic hotspots
  var card = useMemo(function () {
    var _cardProps$values3;
    return cardProps.type !== CARD_TYPES.IMAGE ? cardProps : _objectSpread(_objectSpread({}, cardProps), {}, {
      values: _objectSpread(_objectSpread({}, cardProps.values), {}, {
        // add the calculated dynamic hotspots with x and y coordinates, but filter out the configured dynamic hotstpots
        hotspots: (_cardProps$values3 = cardProps.values) === null || _cardProps$values3 === void 0 || (_cardProps$values3 = _cardProps$values3.hotspots) === null || _cardProps$values3 === void 0 || (_cardProps$values3 = _cardProps$values3.concat(dynamicHotspots)) === null || _cardProps$values3 === void 0 ? void 0 : _cardProps$values3.filter(function (hotspot) {
          return hotspot.type !== 'dynamic';
        })
      })
    });
  }, [cardProps, dynamicHotspots]);
  return /*#__PURE__*/React__default.createElement(DashboardEditorDefaultCardRenderer, {
    card: card,
    availableDimensions: availableDimensions
  });
}, shouldComponentSkipUpdate);
CachedEditorCardRenderer.__docgenInfo = {
  "description": "This component is needed to cache the style object for performance reasons because unfortunately, the style object changes with every render from React Grid Layout",
  "methods": [],
  "displayName": "CachedEditorCardRenderer",
  "props": {
    "style": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "required": false
    }
  }
};
var DashboardEditorCardRenderer$1 = CachedEditorCardRenderer;

export { DashboardEditorCardRenderer$1 as default };
