"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.isFileStateItem = exports.isExternalImageItem = exports.MAX_FILE_SIZE_SUPPORTED_BY_CODEVIEWER = exports.ItemViewerBase = exports.ItemViewer = void 0;
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _reactLoadable = _interopRequireDefault(require("react-loadable"));
var _mediaClient = require("@atlaskit/media-client");
var _compiled = require("@atlaskit/primitives/compiled");
var _reactIntlNext = require("react-intl-next");
var _mediaUi = require("@atlaskit/media-ui");
var _codeViewer = require("@atlaskit/media-ui/codeViewer");
var _mediaClientReact = require("@atlaskit/media-client-react");
var _domain = require("./domain");
var _loading = require("./loading");
var _errorMessage = _interopRequireDefault(require("./errorMessage"));
var _errors = require("./errors");
var _download = require("./download");
var _analyticsNext = require("@atlaskit/analytics-next");
var _commenced = require("./analytics/events/operational/commenced");
var _loadSucceeded = require("./analytics/events/operational/loadSucceeded");
var _analytics = require("./analytics");
var _interactiveImg = require("./viewers/image/interactive-img");
var _archiveViewerLoader = _interopRequireDefault(require("./viewers/archiveSidebar/archiveViewerLoader"));
var _ufoExperiences = require("./analytics/ufoExperiences");
var _customViewer = require("./viewers/customViewer/customViewer");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != (0, _typeof2.default)(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
var ImageViewer = (0, _reactLoadable.default)({
  loader: function loader() {
    return Promise.resolve().then(function () {
      return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_imageViewer" */'./viewers/image'));
    }).then(function (mod) {
      return mod.ImageViewer;
    });
  },
  loading: function loading() {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
});
var VideoViewer = (0, _reactLoadable.default)({
  loader: function loader() {
    return Promise.resolve().then(function () {
      return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_videoViewer" */'./viewers/video'));
    }).then(function (mod) {
      return mod.VideoViewer;
    });
  },
  loading: function loading() {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
});
var AudioViewer = (0, _reactLoadable.default)({
  loader: function loader() {
    return Promise.resolve().then(function () {
      return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_audioViewer" */'./viewers/audio'));
    }).then(function (mod) {
      return mod.AudioViewer;
    });
  },
  loading: function loading() {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
});
var DocViewer = (0, _reactLoadable.default)({
  loader: function loader() {
    return Promise.resolve().then(function () {
      return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_docViewer" */'./viewers/doc'));
    }).then(function (mod) {
      return mod.DocViewer;
    });
  },
  loading: function loading() {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
});
var DocNextViewer = (0, _reactLoadable.default)({
  loader: function loader() {
    return Promise.resolve().then(function () {
      return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_docNextViewer" */'./viewers/doc-next'));
    }).then(function (mod) {
      return mod.DocViewer;
    });
  },
  loading: function loading() {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
});
var CodeViewer = (0, _reactLoadable.default)({
  loader: function loader() {
    return Promise.resolve().then(function () {
      return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_codeViewer" */'./viewers/codeViewer'));
    }).then(function (mod) {
      return mod.CodeViewer;
    });
  },
  loading: function loading() {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
});
var SvgViewer = (0, _reactLoadable.default)({
  loader: function loader() {
    return (
      // @ts-ignore: [PIT-1685] Fails in post-office due to backwards incompatibility issue with React 18
      Promise.resolve().then(function () {
        return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_svgViewer" */'./viewers/svg'));
      }).then(function (mod) {
        return mod.SvgViewer;
      })
    );
  },
  loading: function loading() {
    return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
  }
});
// Consts
var isExternalImageItem = exports.isExternalImageItem = function isExternalImageItem(fileItem) {
  return fileItem === 'external-image';
};
var isFileStateItem = exports.isFileStateItem = function isFileStateItem(fileItem) {
  return !isExternalImageItem(fileItem);
};
var MAX_FILE_SIZE_SUPPORTED_BY_CODEVIEWER = exports.MAX_FILE_SIZE_SUPPORTED_BY_CODEVIEWER = 10 * 1024 * 1024;
var ItemViewerBase = exports.ItemViewerBase = function ItemViewerBase(_ref) {
  var identifier = _ref.identifier,
    showControls = _ref.showControls,
    onClose = _ref.onClose,
    previewCount = _ref.previewCount,
    contextId = _ref.contextId,
    createAnalyticsEvent = _ref.createAnalyticsEvent,
    viewerOptions = _ref.viewerOptions,
    traceContext = _ref.traceContext;
  // States and Refs
  var _useState = (0, _react.useState)(_domain.Outcome.pending()),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    item = _useState2[0],
    setItem = _useState2[1];
  var fileStateFlagsRef = (0, _react.useRef)({
    wasStatusUploading: false,
    wasStatusProcessing: false
  });
  var createAnalyticsEventRef = (0, _react.useRef)(createAnalyticsEvent);
  createAnalyticsEventRef.current = createAnalyticsEvent;

  // Hooks
  var mediaClient = (0, _mediaClientReact.useMediaClient)();
  var _useFileState = (0, _mediaClientReact.useFileState)((0, _mediaClient.isExternalImageIdentifier)(identifier) ? '' : identifier.id, {
      collectionName: (0, _mediaClient.isExternalImageIdentifier)(identifier) ? '' : identifier.collectionName,
      skipRemote: (0, _mediaClient.isExternalImageIdentifier)(identifier)
    }),
    fileState = _useFileState.fileState;
  var renderDownloadButton = (0, _react.useCallback)(function (fileState, error) {
    var collectionName = (0, _mediaClient.isFileIdentifier)(identifier) ? identifier.collectionName : undefined;
    return /*#__PURE__*/_react.default.createElement(_download.ErrorViewDownloadButton, {
      fileState: fileState,
      mediaClient: mediaClient,
      error: error,
      collectionName: collectionName,
      traceContext: traceContext
    });
  }, [mediaClient, identifier, traceContext]);

  // Did mount

  (0, _react.useEffect)(function () {
    if ((0, _mediaClient.isExternalImageIdentifier)(identifier)) {
      return;
    }
    (0, _analytics.fireAnalytics)((0, _commenced.createCommencedEvent)(identifier === null || identifier === void 0 ? void 0 : identifier.id, traceContext), createAnalyticsEventRef.current);
    (0, _ufoExperiences.startMediaFileUfoExperience)();
  }, [identifier, traceContext]);
  (0, _react.useEffect)(function () {
    if ((0, _mediaClient.isExternalImageIdentifier)(identifier)) {
      // external images do not need to talk to our backend,
      // so therefore no need for media-client subscriptions.
      // just set a successful outcome of type "external-image".
      setItem(_domain.Outcome.successful('external-image'));
      return;
    }

    // File Subscription
    if (fileState) {
      var status = fileState.status;
      if (fileState.status !== 'error') {
        // updateFileStateFlag

        if (status === 'processing') {
          fileStateFlagsRef.current.wasStatusProcessing = true;
        } else if (status === 'uploading') {
          fileStateFlagsRef.current.wasStatusUploading = true;
        }
        setItem(_domain.Outcome.successful(fileState));
      } else {
        setItem(_domain.Outcome.failed(new _errors.MediaViewerError('itemviewer-fetch-metadata', (0, _mediaClient.toCommonMediaClientError)(fileState))));
      }
    }
  }, [fileState, identifier]);
  var onSuccess = (0, _react.useCallback)(function () {
    item.whenSuccessful(function (fileItem) {
      if (isFileStateItem(fileItem)) {
        var fileAttributes = (0, _analytics.getFileAttributes)(fileItem);
        (0, _analytics.fireAnalytics)((0, _loadSucceeded.createLoadSucceededEvent)(fileAttributes, traceContext), createAnalyticsEventRef.current);
        (0, _ufoExperiences.succeedMediaFileUfoExperience)({
          fileAttributes: fileAttributes,
          fileStateFlags: fileStateFlagsRef.current
        });
      }
    });
  }, [item, traceContext]);
  var onLoadFail = (0, _react.useCallback)(function (mediaViewerError) {
    setItem(_domain.Outcome.failed(mediaViewerError, fileState));
  }, [fileState]);
  var renderItem = function renderItem(fileItem) {
    var _viewerOptions$custom;
    var collectionName = (0, _mediaClient.isFileIdentifier)(identifier) ? identifier.collectionName : undefined;
    var viewerProps = {
      mediaClient: mediaClient,
      item: fileItem,
      collectionName: collectionName,
      onClose: onClose,
      previewCount: previewCount,
      viewerOptions: viewerOptions,
      traceContext: traceContext
    };
    var customRenderer = viewerOptions === null || viewerOptions === void 0 || (_viewerOptions$custom = viewerOptions.customRenderers) === null || _viewerOptions$custom === void 0 ? void 0 : _viewerOptions$custom.find(function (renderer) {
      return renderer.shouldUseCustomRenderer({
        fileItem: fileItem
      });
    });
    if (customRenderer) {
      return /*#__PURE__*/_react.default.createElement(_customViewer.CustomViewer, (0, _extends2.default)({
        customRendererConfig: customRenderer,
        onError: onLoadFail,
        onSuccess: onSuccess
      }, viewerProps));
    }

    // TODO: fix all of the item errors

    if ((0, _codeViewer.isCodeViewerItem)(fileItem.name, fileItem.mimeType)) {
      //Render error message if code file has size over 10MB.
      //Required by https://product-fabric.atlassian.net/browse/MEX-1788
      if (fileItem.size > MAX_FILE_SIZE_SUPPORTED_BY_CODEVIEWER) {
        return renderError(new _errors.MediaViewerError('codeviewer-file-size-exceeds'), fileItem);
      }
      return /*#__PURE__*/_react.default.createElement(CodeViewer, (0, _extends2.default)({
        onSuccess: onSuccess,
        onError: onLoadFail
      }, viewerProps));
    }
    if ((0, _mediaClient.isFileIdentifier)(identifier) && fileItem.mimeType === 'image/svg+xml') {
      return /*#__PURE__*/_react.default.createElement(SvgViewer, {
        identifier: identifier,
        onLoad: onSuccess,
        onError: onLoadFail,
        onClose: onClose,
        traceContext: traceContext
      });
    }
    var mediaType = fileItem.mediaType;
    switch (mediaType) {
      case 'image':
        return /*#__PURE__*/_react.default.createElement(ImageViewer, (0, _extends2.default)({
          onLoad: onSuccess,
          onError: onLoadFail,
          contextId: contextId
        }, viewerProps));
      case 'audio':
        return /*#__PURE__*/_react.default.createElement(AudioViewer, (0, _extends2.default)({
          showControls: showControls,
          onCanPlay: onSuccess,
          onError: onLoadFail
        }, viewerProps));
      case 'video':
        return /*#__PURE__*/_react.default.createElement(VideoViewer, (0, _extends2.default)({
          identifier: identifier,
          showControls: showControls,
          onCanPlay: onSuccess,
          onError: onLoadFail
        }, viewerProps));
      case 'doc':
        if ((0, _platformFeatureFlags.fg)('media_document_viewer')) {
          return /*#__PURE__*/_react.default.createElement(DocNextViewer, (0, _extends2.default)({
            onSuccess: onSuccess,
            onError: onLoadFail
          }, viewerProps));
        }
        return /*#__PURE__*/_react.default.createElement(DocViewer, (0, _extends2.default)({
          onSuccess: onSuccess,
          onError: onLoadFail
        }, viewerProps));
      case 'archive':
        return /*#__PURE__*/_react.default.createElement(_archiveViewerLoader.default, (0, _extends2.default)({
          onSuccess: onSuccess,
          onError: onLoadFail
        }, viewerProps));
    }
    return renderError(new _errors.MediaViewerError('unsupported'), fileItem);
  };
  var renderError = (0, _react.useCallback)(function (error, fileItem) {
    if (fileItem) {
      var _fileState;
      if (fileItem === 'external-image') {
        // external image error outcome
        _fileState = {
          id: 'external-image',
          status: 'error'
        };
      } else {
        // FileState error outcome
        _fileState = fileItem;
      }
      return /*#__PURE__*/_react.default.createElement(_errorMessage.default, {
        fileId: (0, _mediaClient.isFileIdentifier)(identifier) ? identifier.id : 'undefined',
        error: error,
        fileState: _fileState,
        fileStateFlags: fileStateFlagsRef.current,
        traceContext: traceContext
      }, /*#__PURE__*/_react.default.createElement(_compiled.Text, null, /*#__PURE__*/_react.default.createElement(_reactIntlNext.FormattedMessage, _mediaUi.messages.try_downloading_file)), renderDownloadButton(_fileState, error));
    } else {
      return /*#__PURE__*/_react.default.createElement(_errorMessage.default, {
        fileId: (0, _mediaClient.isFileIdentifier)(identifier) ? identifier.id : 'undefined',
        error: error,
        fileStateFlags: fileStateFlagsRef.current
      });
    }
  }, [identifier, renderDownloadButton, traceContext]);
  return item.match({
    successful: function successful(fileItem) {
      if (fileItem === 'external-image') {
        // render an external image
        var _ref2 = identifier,
          dataURI = _ref2.dataURI,
          name = _ref2.name;
        return /*#__PURE__*/_react.default.createElement(_interactiveImg.InteractiveImg, {
          src: dataURI,
          alt: name !== null && name !== void 0 ? name : '',
          onLoad: function onLoad() {
            (0, _analytics.fireAnalytics)((0, _loadSucceeded.createLoadSucceededEvent)({
              fileId: 'external-image'
            }), createAnalyticsEventRef.current);
            (0, _ufoExperiences.succeedMediaFileUfoExperience)({
              fileAttributes: {
                fileId: 'external-image'
              },
              fileStateFlags: fileStateFlagsRef.current
            });
          },
          onError: function onError() {
            setItem(_domain.Outcome.failed(new _errors.MediaViewerError('imageviewer-external-onerror')));
          }
        });
      } else {
        // render a FileState fetched through media-client
        switch (fileItem.status) {
          case 'processed':
          case 'uploading':
          case 'processing':
            return renderItem(fileItem);
          case 'failed-processing':
            if (fileItem.mediaType === 'doc' && fileItem.mimeType === 'application/pdf') {
              return renderItem(fileItem);
            }
            return renderError(new _errors.MediaViewerError('itemviewer-file-failed-processing-status'), fileItem);
          case 'error':
            return renderError(new _errors.MediaViewerError('itemviewer-file-error-status', (0, _mediaClient.toCommonMediaClientError)(fileItem)), fileItem);
        }
      }
    },
    pending: function pending() {
      return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
    },
    failed: function failed(error) {
      return renderError(error, item.data);
    }
  });
};
var ViewerWithKey = function ViewerWithKey(props) {
  var identifier = props.identifier;
  var key = (0, _mediaClient.isFileIdentifier)(identifier) ? identifier.id : identifier.dataURI;
  return /*#__PURE__*/_react.default.createElement(ItemViewerBase, (0, _extends2.default)({}, props, {
    key: key
  }));
};
var ItemViewer = exports.ItemViewer = (0, _analyticsNext.withAnalyticsEvents)()(ViewerWithKey);