'use strict';

var _extends = require('@babel/runtime/helpers/extends');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var pick = require('../../node_modules/lodash-es/pick.js');
var isNil = require('../../node_modules/lodash-es/isNil.js');
require('core-js/modules/es.symbol.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.includes.js');
require('core-js/modules/es.array.iterator.js');
require('core-js/modules/es.array.join.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');
require('core-js/modules/web.dom-collections.iterator.js');
var React = require('react');
var CardPropTypes = require('../../constants/CardPropTypes.js');
var LayoutConstants = require('../../constants/LayoutConstants.js');
var Card = require('../Card/Card.js');
var cardUtilityFunctions = require('../../utils/cardUtilityFunctions.js');
var editorUtils = require('../DashboardEditor/editorUtils.js');
var Settings = require('../../constants/Settings.js');
var dayjs = require('../../utils/dayjs.js');
var ImageHotspots = require('./ImageHotspots.js');
var ImageUploader = require('./ImageUploader.js');
var iconsReact = require('@carbon/icons-react');

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

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

var _excluded = ["title", "content", "children", "values", "size", "onCardAction", "availableActions", "isEditable", "isExpanded", "isResizable", "error", "isLoading", "maxFileSizeInBytes", "i18n", "i18n", "renderIconByName", "locale", "onUpload", "validateUploadedImage", "onBrowseClick", "testID", "testId", "timeZone"];
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 = _objectSpread(_objectSpread({}, CardPropTypes.CardPropTypes), CardPropTypes.ImageCardPropTypes);
var defaultProps = {
  i18n: {
    loadingDataLabel: 'Loading hotspot data',
    dropContainerLabelText: 'Drag file here or click to upload file',
    dropContainerDescText: 'Max file size is 1MB. Supported file types are: APNG, AVIF, GIF, JPEG, PNG, WebP',
    uploadByURLCancel: 'Cancel',
    uploadByURLButton: 'OK',
    browseImages: 'Add from gallery',
    insertUrl: 'Insert from URL',
    urlInput: 'Type or insert URL',
    errorTitle: 'Upload error: ',
    fileTooLarge: 'Image file is too large',
    wrongFileType: function wrongFileType(accept) {
      return "This file is not one of the accepted file types, ".concat(accept.join(', '));
    }
  },
  locale: 'en',
  timeZone: undefined,
  content: {},
  maxFileSizeInBytes: 1048576,
  accept: null,
  validateUploadedImage: null,
  onUpload: function onUpload() {},
  onBrowseClick: null,
  renderIconByName: function renderIconByName(iconName, iconProps) {
    // first search the validHotspot Icons
    var matchingHotspotIcon = editorUtils.validHotspotIcons.find(function (icon) {
      return icon.id === iconName;
    });

    // then search the validThresholdIcons
    var matchingThresholdIcon = editorUtils.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, _objectSpread(_objectSpread({}, iconProps), {}, {
      title: 'Warning'
    }));
    // otherwise default to Warning24
    // eslint-disable-next-line react/prop-types
    return /*#__PURE__*/React__default.default.createElement("div", {
      style: {
        color: iconProps.fill
      }
    }, iconToRender);
  },
  // TODO: fix this after v3.
  // since the default card props aren't merged with the default image card props the
  // testId is technically undefined here, so we're matching the Card default to maintain backwards compat.
  testId: 'ImageCard'
};
var ImageCard = function ImageCard(_ref) {
  var title = _ref.title,
    content = _ref.content,
    children = _ref.children,
    values = _ref.values,
    size = _ref.size,
    onCardAction = _ref.onCardAction,
    availableActions = _ref.availableActions,
    isEditable = _ref.isEditable,
    isExpanded = _ref.isExpanded,
    isResizable = _ref.isResizable,
    error = _ref.error,
    isLoading = _ref.isLoading,
    maxFileSizeInBytes = _ref.maxFileSizeInBytes,
    i18n = _ref.i18n,
    loadingDataLabel = _ref.i18n.loadingDataLabel,
    renderIconByName = _ref.renderIconByName,
    locale = _ref.locale,
    onUpload = _ref.onUpload,
    validateUploadedImage = _ref.validateUploadedImage,
    onBrowseClick = _ref.onBrowseClick,
    testID = _ref.testID,
    testId = _ref.testId,
    timeZone = _ref.timeZone,
    others = _objectWithoutProperties__default.default(_ref, _excluded);
  var effectiveTimezone = timeZone || dayjs.default.tz.guess();
  dayjs.default.tz.setDefault(effectiveTimezone);
  var _useState = React.useState(content),
    _useState2 = _slicedToArray__default.default(_useState, 2),
    imgContent = _useState2[0],
    setImgContent = _useState2[1];
  var hotspots = values ? values.hotspots || [] : [];
  var _ref2 = content || {},
    hasInsertFromUrl = _ref2.hasInsertFromUrl;
  var mergedI18n = React.useMemo(function () {
    return _objectSpread(_objectSpread({}, defaultProps.i18n), i18n);
  }, [i18n]);
  React.useEffect(function () {
    setImgContent(content);
  }, [content]);
  var handleOnUpload = function handleOnUpload(imageData) {
    var _imageData$files;
    var newData = _objectSpread(_objectSpread({}, imgContent), {}, {
      src: imageData.dataURL,
      id: (_imageData$files = imageData.files) === null || _imageData$files === void 0 || (_imageData$files = _imageData$files.addedFiles[0]) === null || _imageData$files === void 0 ? void 0 : _imageData$files.name
    });
    onCardAction(others.id, LayoutConstants.CARD_ACTIONS.ON_CARD_CHANGE, {
      content: {
        id: {
          $set: newData.id
        },
        src: {
          $set: newData.src
        },
        imgState: {
          $set: 'new'
        }
      }
    });
    onUpload(imageData.files);
    setImgContent(newData);
  };

  // Checks size property against new size naming convention and reassigns to closest supported size if necessary.
  var newSize = cardUtilityFunctions.getUpdatedCardSize(size);
  var supportedSizes = [LayoutConstants.CARD_SIZES.MEDIUMTHIN, LayoutConstants.CARD_SIZES.MEDIUM, LayoutConstants.CARD_SIZES.MEDIUMWIDE, LayoutConstants.CARD_SIZES.LARGE, LayoutConstants.CARD_SIZES.LARGEWIDE];
  var supportedSize = supportedSizes.includes(newSize);
  var mergedAvailableActions = _objectSpread({
    expand: supportedSize
  }, availableActions);
  var isCardLoading = isNil(imgContent.src) && !isEditable && !error;
  var resizeHandles = isResizable ? cardUtilityFunctions.getResizeHandles(children) : [];
  return /*#__PURE__*/React__default.default.createElement(Card.default, _extends__default.default({
    title: title,
    size: newSize,
    onCardAction: onCardAction,
    availableActions: mergedAvailableActions,
    isLoading: isCardLoading // only show the spinner if we don't have an image
    ,
    isExpanded: isExpanded,
    isEditable: isEditable,
    resizeHandles: resizeHandles
    // TODO: remove deprecated testID prop in v3.
    ,
    testId: testID || testId,
    locale: locale,
    timeZone: effectiveTimezone
  }, others, {
    error: error,
    i18n: mergedI18n
  }), !isCardLoading ? function (// Get width and height from parent card
  _ref3 // eslint-disable-line react/prop-types
  ) {
    var width = _ref3.width,
      height = _ref3.height;
    return /*#__PURE__*/React__default.default.createElement("div", {
      className: "".concat(iotPrefix, "--image-card__wrapper")
    }, isEditable && !imgContent.src ? /*#__PURE__*/React__default.default.createElement(ImageUploader, {
      onBrowseClick: onBrowseClick,
      width: width,
      height: height,
      maxFileSizeInBytes: maxFileSizeInBytes,
      onUpload: handleOnUpload,
      i18n: pick(mergedI18n, 'dropContainerLabelText', 'dropContainerDescText', 'uploadByURLCancel', 'uploadByURLButton', 'browseImages', 'insertUrl', 'urlInput', 'fileTooLarge', 'errorTitle', 'wrongFileType'),
      hasInsertFromUrl: hasInsertFromUrl,
      validateUploadedImage: validateUploadedImage
      // TODO: remove deprecated testID prop in v3.
      ,
      testId: "".concat(testID || testId, "-image-uploader")
    }) : imgContent.src ? /*#__PURE__*/React__default.default.createElement(ImageHotspots.default
    // Key regen needed for stories that modifies the displayOption
    , _extends__default.default({
      key: imgContent === null || imgContent === void 0 ? void 0 : imgContent.displayOption
    }, imgContent, {
      // Adjust for side padding of iot-image-card__wrapper + border of iot-card--wrapper
      width: width - (16 * 2 + 4)
      // Adjust for bottom padding of iot-image-card__wrapper + border of iot-card--wrapper
      ,
      height: height - (16 + 4),
      isExpanded: isExpanded,
      hotspots: hotspots,
      isHotspotDataLoading: isLoading,
      loadingHotspotsLabel: loadingDataLabel,
      renderIconByName: renderIconByName,
      locale: locale,
      i18n: pick(mergedI18n, 'zoomIn', 'zoomOut', 'zoomToFit', 'titlePlaceholderText', 'titleEditableHintText')
      // TODO: remove deprecated testID prop in v3.
      ,
      testId: "".concat(testID || testId, "-image-hotspots")
    })) : /*#__PURE__*/React__default.default.createElement("div", {
      // TODO: remove deprecated testID prop in v3.
      "data-testid": "".concat(testID || testId, "-empty"),
      className: "".concat(iotPrefix, "--image-card__empty")
    }, /*#__PURE__*/React__default.default.createElement(iconsReact.Image, {
      size: 32,
      width: 250,
      height: 250,
      fill: "gray"
    })));
  } : null);
};
ImageCard.propTypes = propTypes;
ImageCard.defaultProps = defaultProps;
ImageCard.__docgenInfo = {
  "description": "",
  "methods": [],
  "displayName": "ImageCard",
  "props": {
    "i18n": {
      "defaultValue": {
        "value": "{\n  loadingDataLabel: 'Loading hotspot data',\n  dropContainerLabelText: 'Drag file here or click to upload file',\n  dropContainerDescText:\n    'Max file size is 1MB. Supported file types are: APNG, AVIF, GIF, JPEG, PNG, WebP',\n  uploadByURLCancel: 'Cancel',\n  uploadByURLButton: 'OK',\n  browseImages: 'Add from gallery',\n  insertUrl: 'Insert from URL',\n  urlInput: 'Type or insert URL',\n  errorTitle: 'Upload error: ',\n  fileTooLarge: 'Image file is too large',\n  wrongFileType: (accept) =>\n    `This file is not one of the accepted file types, ${accept.join(', ')}`,\n}",
        "computed": false
      },
      "required": false
    },
    "locale": {
      "defaultValue": {
        "value": "'en'",
        "computed": false
      },
      "required": false
    },
    "timeZone": {
      "defaultValue": {
        "value": "undefined",
        "computed": true
      },
      "required": false
    },
    "content": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "required": false
    },
    "maxFileSizeInBytes": {
      "defaultValue": {
        "value": "1048576",
        "computed": false
      },
      "required": false
    },
    "accept": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "validateUploadedImage": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "onUpload": {
      "defaultValue": {
        "value": "() => {}",
        "computed": false
      },
      "required": false
    },
    "onBrowseClick": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "required": false
    },
    "renderIconByName": {
      "defaultValue": {
        "value": "(iconName, iconProps) => {\n  // first search the validHotspot Icons\n  const matchingHotspotIcon = validHotspotIcons.find((icon) => icon.id === iconName);\n\n  // then search the validThresholdIcons\n  const matchingThresholdIcon = validThresholdIcons.find((icon) => icon.name === iconName);\n  const iconToRender = matchingHotspotIcon\n    ? React.createElement(matchingHotspotIcon.icon, {\n        ...iconProps,\n        title: matchingHotspotIcon.text,\n      })\n    : matchingThresholdIcon\n    ? React.cloneElement(matchingThresholdIcon.carbonIcon, {\n        ...iconProps,\n        title: matchingThresholdIcon.name,\n      })\n    : React.createElement(Warning, {\n        ...iconProps,\n        title: 'Warning',\n      });\n  // otherwise default to Warning24\n  // eslint-disable-next-line react/prop-types\n  return <div style={{ color: iconProps.fill }}>{iconToRender}</div>;\n}",
        "computed": false
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'ImageCard'",
        "computed": false
      },
      "required": false
    }
  },
  "composes": ["../../constants/CardPropTypes"]
};
var ImageCard$1 = ImageCard;

module.exports = ImageCard$1;
