"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MediaInlineImageCardInternal = exports.MediaInlineImageCard = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _react2 = require("@emotion/react");
var _reactDom = _interopRequireDefault(require("react-dom"));
var _reactIntlNext = require("react-intl-next");
var _useAnalyticsEvents2 = require("@atlaskit/analytics-next/useAnalyticsEvents");
var _mediaCard = require("@atlaskit/media-card");
var _mediaClient = require("@atlaskit/media-client");
var _mediaClientReact = require("@atlaskit/media-client-react");
var _mediaViewer = require("@atlaskit/media-viewer");
var _experiments = require("@atlaskit/tmp-editor-statsig/experiments");
var _mediaInlineCard = require("../messages/media-inline-card");
var _constants = require("./constants");
var _inlineImageCard = require("./inline-image-card");
var _inlineImageWrapper = require("./inline-image-wrapper");
var _errorView = require("./views/error-view");
var _loadingView = require("./views/loading-view");
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) { (0, _defineProperty2.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; } /**
 * @jsxRuntime classic
 * @jsx jsx
 */ // eslint-disable-next-line @atlaskit/ui-styling-standard/use-compiled, @typescript-eslint/consistent-type-imports -- Ignored via go/DSP-18766; jsx required at runtime for @jsxRuntime classic
var MediaInlineImageCardInternal = exports.MediaInlineImageCardInternal = function MediaInlineImageCardInternal(_ref) {
  var mediaClient = _ref.mediaClient,
    identifier = _ref.identifier,
    isSelected = _ref.isSelected,
    intl = _ref.intl,
    alt = _ref.alt,
    isLazy = _ref.isLazy,
    width = _ref.width,
    height = _ref.height,
    border = _ref.border,
    ssr = _ref.ssr,
    serializeDataAttrs = _ref.serializeDataAttrs,
    shouldOpenMediaViewer = _ref.shouldOpenMediaViewer,
    isViewOnly = _ref.isViewOnly;
  var _useState = (0, _react.useState)(),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    fileState = _useState2[0],
    setFileState = _useState2[1];
  var _useState3 = (0, _react.useState)(),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    subscribeError = _useState4[0],
    setSubscribeError = _useState4[1];
  var _useState5 = (0, _react.useState)(false),
    _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
    isFailedEventSent = _useState6[0],
    setIsFailedEventSent = _useState6[1];
  var _useState7 = (0, _react.useState)(false),
    _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
    isSucceededEventSent = _useState8[0],
    setIsSucceededEventSent = _useState8[1];
  var _useState9 = (0, _react.useState)(false),
    _useState0 = (0, _slicedToArray2.default)(_useState9, 2),
    isMediaViewerVisible = _useState0[0],
    setMediaViewerVisible = _useState0[1];
  var _ref2 = intl || (0, _reactIntlNext.createIntl)({
      locale: 'en'
    }),
    formatMessage = _ref2.formatMessage;
  var _useAnalyticsEvents = (0, _useAnalyticsEvents2.useAnalyticsEvents)(),
    createAnalyticsEvent = _useAnalyticsEvents.createAnalyticsEvent;
  var fireFailedOperationalEvent = function fireFailedOperationalEvent() {
    var error = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new _mediaCard.MediaCardError('missing-error-data');
    var failReason = arguments.length > 1 ? arguments[1] : undefined;
    if (!isFailedEventSent && fileState) {
      setIsFailedEventSent(true);
      (0, _mediaCard.fireFailedMediaInlineEvent)(fileState, error, failReason, createAnalyticsEvent);
    }
  };
  var fireSucceededOperationalEvent = function fireSucceededOperationalEvent() {
    if (!isSucceededEventSent && fileState) {
      setIsSucceededEventSent(true);
      (0, _mediaCard.fireSucceededMediaInlineEvent)(fileState, createAnalyticsEvent);
    }
  };
  (0, _react.useEffect)(function () {
    if (mediaClient) {
      var subscription = mediaClient.file.getFileState(identifier.id, {
        collectionName: identifier.collectionName
      }).subscribe({
        next: function next(fileState) {
          setFileState(fileState);
          setSubscribeError(undefined);
        },
        error: function error(e) {
          setSubscribeError(e);
        }
      });
      return function () {
        subscription.unsubscribe();
      };
    }
  }, [identifier, mediaClient]);
  var content = function content(dimensions) {
    if (!mediaClient) {
      return (0, _react2.jsx)(_loadingView.InlineImageCardLoadingView, null);
    }
    if (!ssr) {
      if (subscribeError) {
        var isUploading = (fileState === null || fileState === void 0 ? void 0 : fileState.status) === 'uploading';
        var errorMessage = isUploading ? _mediaInlineCard.messages.failedToUpload : _mediaInlineCard.messages.unableToLoadContent;
        var errorReason = (fileState === null || fileState === void 0 ? void 0 : fileState.status) === 'uploading' ? 'upload' : 'metadata-fetch';
        fireFailedOperationalEvent(new _mediaCard.MediaCardError(errorReason, subscribeError));
        return (0, _react2.jsx)(_errorView.InlineImageCardErrorView, {
          message: formatMessage(errorMessage)
        });
      }
      if (!fileState || (fileState === null || fileState === void 0 ? void 0 : fileState.status) === 'uploading') {
        return (0, _react2.jsx)(_loadingView.InlineImageCardLoadingView, null);
      }
      if (fileState.status === 'error') {
        fireFailedOperationalEvent(new _mediaCard.MediaCardError('error-file-state', new Error(fileState.message)));
        return (0, _react2.jsx)(_errorView.InlineImageCardErrorView, {
          message: formatMessage(_mediaInlineCard.messages.unableToLoadContent)
        });
      } else if (fileState.status === 'failed-processing') {
        fireFailedOperationalEvent(undefined, 'failed-processing');
        return (0, _react2.jsx)(_errorView.InlineImageCardErrorView, {
          message: formatMessage(_mediaInlineCard.messages.unableToLoadContent)
        });
      } else if (!fileState.name) {
        fireFailedOperationalEvent(new _mediaCard.MediaCardError('metadata-fetch', new _mediaClient.FileFetcherError('emptyFileName', {
          id: fileState.id
        })));
        return (0, _react2.jsx)(_errorView.InlineImageCardErrorView, {
          message: formatMessage(_mediaInlineCard.messages.unableToLoadContent)
        });
      }
      if (fileState.status === 'processed') {
        fireSucceededOperationalEvent();
      }
    }
    return (0, _react2.jsx)(_mediaClientReact.MediaClientContext.Provider, {
      value: mediaClient
    }, (0, _react2.jsx)(_inlineImageCard.InlineImageCard, {
      dimensions: dimensions,
      identifier: identifier
      // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- Ignored via go/ees017 (to be fixed)
      ,
      renderError: function renderError() {
        return (0, _react2.jsx)(_errorView.InlineImageCardErrorView, {
          message: formatMessage(_mediaInlineCard.messages.unableToLoadContent)
        });
      },
      alt: alt,
      ssr: ssr === null || ssr === void 0 ? void 0 : ssr.mode,
      isLazy: isLazy,
      crop: true,
      stretch: false
    }));
  };
  var aspectRatio = (0, _react.useMemo)(function () {
    return width && height ? width / height : undefined;
  }, [width, height]);

  /**
   * scaledDimensions is used to define the correct media size fetched from media service
   * inline images will only ever be rendered at a maximum height of H1 and so scaled dimensions
   * will only ever return a width and height where the height has a maximum height of H1
   */
  var scaledDimension = (0, _react.useMemo)(function () {
    if (!width || !height || !aspectRatio) {
      return {
        width: width,
        height: height
      };
    }
    return {
      width: Math.round(aspectRatio * _constants.referenceHeights['h1']),
      height: _constants.referenceHeights['h1']
    };
  }, [width, height, aspectRatio]);
  var htmlAttributes = (0, _react.useMemo)(function () {
    if (serializeDataAttrs) {
      var resolvedAttrs = fileState && fileState.status !== 'error' ? {
        'data-file-size': fileState.size,
        'data-file-mime-type': fileState.mimeType,
        'data-file-name': fileState.name
      } : {};
      return _objectSpread({
        'data-type': 'image',
        'data-node-type': 'mediaInline',
        'data-id': identifier.id,
        'data-collection': identifier.collectionName,
        'data-width': width,
        'data-height': height,
        'data-alt': alt
      }, resolvedAttrs);
    }
    return {};
  }, [alt, fileState, height, identifier, width, serializeDataAttrs]);
  var onMediaInlineImageClick = (0, _react.useCallback)(function (e) {
    if (shouldOpenMediaViewer) {
      setMediaViewerVisible(true);
    }

    // In edit mode (node content wrapper has contenteditable set to true), link redirection is disabled by default
    // We need to call "stopPropagation" here in order to prevent in editor view mode, the browser from navigating to
    // another URL if the media node is wrapped in a link mark.
    if (isViewOnly && (0, _experiments.editorExperiment)('platform_editor_controls', 'variant1')) {
      e.preventDefault();
    }
  }, [shouldOpenMediaViewer, isViewOnly]);
  var onMediaInlinePreviewClose = (0, _react.useCallback)(function () {
    setMediaViewerVisible(false);
  }, []);
  var mediaViewer = (0, _react.useMemo)(function () {
    if (isMediaViewerVisible && mediaClient !== null && mediaClient !== void 0 && mediaClient.mediaClientConfig) {
      return /*#__PURE__*/_reactDom.default.createPortal((0, _react2.jsx)(_mediaViewer.MediaViewer, {
        collectionName: identifier.collectionName || ''
        // eslint-disable-next-line @atlassian/perf-linting/no-unstable-inline-props -- Ignored via go/ees017 (to be fixed)
        ,
        items: [identifier],
        mediaClientConfig: mediaClient === null || mediaClient === void 0 ? void 0 : mediaClient.mediaClientConfig,
        selectedItem: identifier,
        onClose: onMediaInlinePreviewClose
      }), document.body);
    }
    return null;
  }, [identifier, isMediaViewerVisible, mediaClient === null || mediaClient === void 0 ? void 0 : mediaClient.mediaClientConfig, onMediaInlinePreviewClose]);
  return (0, _react2.jsx)(_react.Fragment, null, (0, _react2.jsx)(_inlineImageWrapper.InlineImageWrapper, {
    isSelected: isSelected,
    aspectRatio: aspectRatio,
    borderColor: border === null || border === void 0 ? void 0 : border.borderColor,
    borderSize: border === null || border === void 0 ? void 0 : border.borderSize,
    htmlAttrs: htmlAttributes,
    onClick: onMediaInlineImageClick
  }, content(scaledDimension)), mediaViewer);
};
var MediaInlineImageCard = exports.MediaInlineImageCard = (0, _reactIntlNext.injectIntl)(MediaInlineImageCardInternal, {
  enforceContext: false
});