'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _extends = require('@babel/runtime/helpers/extends');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var isNil = require('../../node_modules/lodash-es/isNil.js');
var isEqual = require('../../node_modules/lodash-es/isEqual.js');
var omit = require('../../node_modules/lodash-es/omit.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.symbol.description.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.iterator.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/web.dom-collections.for-each.js');
require('core-js/modules/web.dom-collections.iterator.js');
var React = require('react');
var update = require('immutability-helper');
var usePrevious = require('../../hooks/usePrevious.js');
var LayoutConstants = require('../../constants/LayoutConstants.js');
var editorUtils = require('./editorUtils.js');
var DashboardEditorDefaultCardRenderer = require('./DashboardEditorDefaultCardRenderer.js');

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

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var _extends__default = /*#__PURE__*/_interopDefault(_extends);
var _slicedToArray__default = /*#__PURE__*/_interopDefault(_slicedToArray);
var _objectWithoutProperties__default = /*#__PURE__*/_interopDefault(_objectWithoutProperties);
var React__default = /*#__PURE__*/_interopDefault(React);
var update__default = /*#__PURE__*/_interopDefault(update);

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__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; }

/**
 *
 * 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__default.default(_ref, _excluded);
  var _useState = React.useState(style),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    cachedStyle = _useState2[0],
    setCachedStyle = _useState2[1];
  var _useState3 = React.useState(children),
    _useState4 = _slicedToArray__default.default(_useState3, 2),
    cachedChildren = _useState4[0],
    setCachedChildren = _useState4[1];
  var previousStyle = usePrevious.usePrevious(style);

  // Unfortunately the react-grid-layout creates a new style object every render
  React.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
  React.useEffect(function () {
    setCachedChildren(children);
  },
  // eslint-disable-next-line react-hooks/exhaustive-deps
  [others.isResizable]);
  return /*#__PURE__*/React__default.default.createElement(DashboardEditorCardRenderer, _extends__default.default({}, 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.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__default.default(_ref2, _excluded2);
  // We have to keep track of our dynamic hotspots here
  var _useState5 = React.useState([]),
    _useState6 = _slicedToArray__default.default(_useState5, 2),
    dynamicHotspots = _useState6[0],
    setDynamicHotspots = _useState6[1];
  var handleOnCardAction = React.useCallback(function (id, actionId, payload) {
    if (actionId === LayoutConstants.CARD_ACTIONS.CLONE_CARD) {
      onDuplicate(id);
    } else if (actionId === LayoutConstants.CARD_ACTIONS.DELETE_CARD) {
      onRemove(id);
    } else if (actionId === LayoutConstants.CARD_ACTIONS.ON_CARD_CHANGE) {
      onCardChange(update__default.default(cardConfig, payload));
    }
  }, [cardConfig, onCardChange, onDuplicate, onRemove]);
  var handleOnCardKeyDown = React.useCallback(function (e) {
    editorUtils.handleKeyDown(e, setSelectedCardId, cardConfig);
  }, [cardConfig, setSelectedCardId]);
  var handleOnCardMouseDown = React.useCallback(function (e) {
    editorUtils.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 = React.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 === LayoutConstants.CARD_TYPES.IMAGE && isNil((_cardConfig$content = cardConfig.content) === null || _cardConfig$content === void 0 ? void 0 : _cardConfig$content.src) ? onShowImageGallery : undefined,
      validateUploadedImage: cardConfig.type === LayoutConstants.CARD_TYPES.IMAGE ? onValidateUploadedImage : undefined
    });
  }, [baseClassName, cardConfig, handleOnCardAction, handleOnCardKeyDown, handleOnCardMouseDown, i18n, isSelected, onShowImageGallery, onValidateUploadedImage, renderIconByName, shouldUseTranslatedLabels, style]);
  React.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 = React.useMemo(function () {
    var _cardProps$values3;
    return cardProps.type !== LayoutConstants.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.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;

module.exports = DashboardEditorCardRenderer$1;
