"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ImageViewer = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _mediaClient = require("@atlaskit/media-client");
var _mediaCommon = require("@atlaskit/media-common");
var _mediaUi = require("@atlaskit/media-ui");
var _domain = require("../../domain");
var _errors = require("../../errors");
var _interactiveImg = require("./interactive-img");
var _baseViewer = require("../base-viewer");
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2.default)(o), (0, _possibleConstructorReturn2.default)(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2.default)(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function processedFileStateToMediaItem(file) {
  return {
    type: 'file',
    details: {
      id: file.id
    }
  };
}
var ImageViewer = exports.ImageViewer = /*#__PURE__*/function (_BaseViewer) {
  function ImageViewer() {
    var _this;
    (0, _classCallCheck2.default)(this, ImageViewer);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, ImageViewer, [].concat(args));
    (0, _defineProperty2.default)(_this, "onLoad", function () {
      _this.props.onLoad();
      _this.onMediaDisplayed();
    });
    (0, _defineProperty2.default)(_this, "onImgError", function () {
      _this.props.onError(new _errors.MediaViewerError('imageviewer-src-onerror'));
    });
    return _this;
  }
  (0, _inherits2.default)(ImageViewer, _BaseViewer);
  return (0, _createClass2.default)(ImageViewer, [{
    key: "initialState",
    get: function get() {
      return {
        content: _domain.Outcome.pending()
      };
    }
  }, {
    key: "init",
    value: function () {
      var _init = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() {
        var _this$props, fileState, mediaClient, collectionName, traceContext, controller, orientation, objectUrl, originalBinaryImageUrl, isLocalFileReference, preview, _yield$preview, value, origin, item, response, imgError;
        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _this$props = this.props, fileState = _this$props.item, mediaClient = _this$props.mediaClient, collectionName = _this$props.collectionName, traceContext = _this$props.traceContext;
              if (!(0, _mediaClient.isErrorFileState)(fileState)) {
                _context.next = 3;
                break;
              }
              return _context.abrupt("return");
            case 3:
              controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
              _context.prev = 4;
              orientation = 1;
              isLocalFileReference = false;
              preview = fileState.preview;
              if (!preview) {
                _context.next = 25;
                break;
              }
              _context.next = 11;
              return preview;
            case 11:
              _yield$preview = _context.sent;
              value = _yield$preview.value;
              origin = _yield$preview.origin;
              if (!(value instanceof Blob)) {
                _context.next = 22;
                break;
              }
              _context.next = 17;
              return (0, _mediaUi.getOrientation)(value);
            case 17:
              orientation = _context.sent;
              objectUrl = URL.createObjectURL(value);
              isLocalFileReference = origin === 'local';
              _context.next = 23;
              break;
            case 22:
              objectUrl = value;
            case 23:
              _context.next = 38;
              break;
            case 25:
              if (!(0, _mediaClient.isImageRepresentationReady)(fileState)) {
                _context.next = 36;
                break;
              }
              item = processedFileStateToMediaItem(fileState);
              response = mediaClient.getImage(item.details.id, {
                collection: collectionName,
                mode: 'fit'
              }, controller, true, traceContext);
              this.cancelImageFetch = function () {
                return controller === null || controller === void 0 ? void 0 : controller.abort();
              };
              _context.t0 = URL;
              _context.next = 32;
              return response;
            case 32:
              _context.t1 = _context.sent;
              objectUrl = _context.t0.createObjectURL.call(_context.t0, _context.t1);
              _context.next = 38;
              break;
            case 36:
              this.setState({
                content: _domain.Outcome.pending()
              });
              return _context.abrupt("return");
            case 38:
              if (!(!isLocalFileReference &&
              // objectUrl at this point is binary file already
              !(0, _mediaClient.isErrorFileState)(fileState) && fileState.status !== 'uploading' && fileState.mediaType === 'image' && (0, _mediaCommon.isImageMimeTypeSupportedByBrowser)(fileState.mimeType))) {
                _context.next = 42;
                break;
              }
              _context.next = 41;
              return mediaClient.file.getFileBinaryURL(fileState.id, collectionName);
            case 41:
              originalBinaryImageUrl = _context.sent;
            case 42:
              this.setState({
                content: _domain.Outcome.successful({
                  objectUrl: objectUrl,
                  orientation: orientation,
                  originalBinaryImageUrl: originalBinaryImageUrl
                })
              });
              _context.next = 48;
              break;
            case 45:
              _context.prev = 45;
              _context.t2 = _context["catch"](4);
              // TODO : properly handle aborted requests (MS-2843)
              if (!(controller !== null && controller !== void 0 && controller.signal.aborted)) {
                imgError = new _errors.MediaViewerError('imageviewer-fetch-url', _context.t2 instanceof Error ? _context.t2 : undefined);
                this.setState({
                  content: _domain.Outcome.failed(imgError)
                });
                this.props.onError(imgError);
              }
            case 48:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[4, 45]]);
      }));
      function init() {
        return _init.apply(this, arguments);
      }
      return init;
    }()
  }, {
    key: "release",
    value: function release() {
      var _this2 = this;
      if (this.cancelImageFetch) {
        this.cancelImageFetch();
      }
      this.state.content.whenSuccessful(function (_ref) {
        var objectUrl = _ref.objectUrl;
        _this2.revokeObjectUrl(objectUrl);
      });
    }

    // This method is spied on by some test cases, so don't rename or remove it.
  }, {
    key: "revokeObjectUrl",
    value: function revokeObjectUrl(objectUrl) {
      URL.revokeObjectURL(objectUrl);
    }
  }, {
    key: "renderSuccessful",
    value: function renderSuccessful(content) {
      var _this$props2 = this.props,
        item = _this$props2.item,
        onClose = _this$props2.onClose,
        contextId = _this$props2.contextId,
        collectionName = _this$props2.collectionName;
      if ((0, _mediaClient.isErrorFileState)(item)) {
        return null;
      }
      var src = contextId ? (0, _mediaClient.addFileAttrsToUrl)(content.objectUrl, {
        id: item.id,
        contextId: contextId,
        collection: collectionName
      }) : content.objectUrl;
      return /*#__PURE__*/_react.default.createElement(_interactiveImg.InteractiveImg, {
        onLoad: this.onLoad,
        onError: this.onImgError,
        src: src,
        alt: item.name,
        originalBinaryImageSrc: content.originalBinaryImageUrl,
        orientation: content.orientation,
        onClose: onClose
      });
    }
  }]);
}(_baseViewer.BaseViewer);