"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getArchiveEntriesFromFileState = exports.ArchiveViewerBase = exports.ArchiveViewer = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
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 _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _react = _interopRequireDefault(require("react"));
var _unzipit = require("unzipit");
var _reactIntlNext = require("react-intl-next");
var _mediaUi = require("@atlaskit/media-ui");
var _codeViewer = require("@atlaskit/media-ui/codeViewer");
var _compiled = require("@atlaskit/primitives/compiled");
var _domain = require("../../domain");
var _styleWrappers = require("../../styleWrappers");
var _audioMediaServicesAudio = _interopRequireDefault(require("@atlaskit/icon/core/migration/audio--media-services-audio"));
var _errorMessage = _interopRequireDefault(require("../../errorMessage"));
var _baseViewer = require("../base-viewer");
var _interactiveImg = require("../image/interactive-img");
var _pdfRenderer = require("../doc/pdfRenderer");
var _styleWrappers2 = require("./styleWrappers");
var _archiveSidebarRenderer = _interopRequireDefault(require("./archive-sidebar-renderer"));
var _utils = require("../../utils");
var _loading = require("../../loading");
var _consts = require("./consts");
var _analyticsNext = require("@atlaskit/analytics-next");
var _analytics = require("../../analytics");
var _errors = require("../../errors");
var _zipEntryLoadSucceeded = require("../../analytics/events/operational/zipEntryLoadSucceeded");
var _zipEntryLoadFailed = require("../../analytics/events/operational/zipEntryLoadFailed");
var _codeViewerRenderer = require("../codeViewer/codeViewerRenderer");
var _util = require("../codeViewer/util");
var _itemViewer = require("../../item-viewer");
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; }
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; })(); } /* eslint-disable @atlaskit/design-system/ensure-design-token-usage */
var getArchiveEntriesFromFileState = exports.getArchiveEntriesFromFileState = /*#__PURE__*/function () {
  var _ref = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(fileState, mediaClient, collectionName) {
    var url, reader, archive;
    return _regenerator.default.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return mediaClient.file.getFileBinaryURL(fileState.id, collectionName);
        case 2:
          url = _context.sent;
          reader = new _unzipit.HTTPRangeReader(url);
          _context.next = 6;
          return (0, _utils.rejectAfter)(function () {
            return (0, _unzipit.unzip)(reader);
          });
        case 6:
          archive = _context.sent;
          return _context.abrupt("return", archive);
        case 8:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return function getArchiveEntriesFromFileState(_x, _x2, _x3) {
    return _ref.apply(this, arguments);
  };
}();
var ArchiveViewerBase = exports.ArchiveViewerBase = /*#__PURE__*/function (_BaseViewer) {
  function ArchiveViewerBase() {
    var _this;
    (0, _classCallCheck2.default)(this, ArchiveViewerBase);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, ArchiveViewerBase, [].concat(args));
    (0, _defineProperty2.default)(_this, "onError", function (error, entry) {
      _this.props.onError(error);
      _this.setState({
        content: _domain.Outcome.successful(_objectSpread(_objectSpread({}, _this.state.content.data), {}, {
          selectedArchiveEntry: entry,
          error: error
        }))
      });
    });
    (0, _defineProperty2.default)(_this, "onSelectedArchiveEntryChange", /*#__PURE__*/function () {
      var _ref2 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(selectedArchiveEntry) {
        var src, codeViewerSrc, isCodeMimeType, blob;
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _this.setState({
                content: _domain.Outcome.successful(_objectSpread(_objectSpread({}, _this.state.content.data), {}, {
                  selectedArchiveEntry: undefined,
                  hasLoadedEntries: false // displays a nice loading spinner for the content viewer
                }))
              });
              src = '';
              codeViewerSrc = '';
              isCodeMimeType = (0, _codeViewer.isCodeViewerItem)(selectedArchiveEntry.name, (0, _utils.getMimeTypeFromFilename)(selectedArchiveEntry.name));
              if (selectedArchiveEntry.isDirectory) {
                _context2.next = 19;
                break;
              }
              _context2.prev = 5;
              _context2.next = 8;
              return (0, _utils.rejectAfter)(function () {
                return selectedArchiveEntry.blob();
              }, 10000);
            case 8:
              blob = _context2.sent;
              src = URL.createObjectURL(blob);
              if (!isCodeMimeType) {
                _context2.next = 14;
                break;
              }
              _context2.next = 13;
              return (0, _utils.rejectAfter)(function () {
                return blob.text();
              });
            case 13:
              codeViewerSrc = _context2.sent;
            case 14:
              _context2.next = 19;
              break;
            case 16:
              _context2.prev = 16;
              _context2.t0 = _context2["catch"](5);
              return _context2.abrupt("return", _this.onError(new _errors.ArchiveViewerError(_context2.t0.message === _consts.ENCRYPTED_ENTRY_ERROR_MESSAGE ? 'archiveviewer-encrypted-entry' : 'archiveviewer-create-url', _context2.t0), selectedArchiveEntry));
            case 19:
              _this.setState({
                content: _domain.Outcome.successful(_objectSpread(_objectSpread({}, _this.state.content.data), {}, {
                  selectedArchiveEntry: selectedArchiveEntry,
                  src: src,
                  name: selectedArchiveEntry.name,
                  isDirectory: selectedArchiveEntry.isDirectory,
                  error: undefined,
                  codeViewerSrc: codeViewerSrc,
                  isCodeMimeType: isCodeMimeType,
                  hasLoadedEntries: true
                }))
              });
            case 20:
            case "end":
              return _context2.stop();
          }
        }, _callee2, null, [[5, 16]]);
      }));
      return function (_x4) {
        return _ref2.apply(this, arguments);
      };
    }());
    (0, _defineProperty2.default)(_this, "onHeaderClicked", function () {
      // This will set the preview to show the Folder icon
      _this.setState({
        content: _domain.Outcome.successful(_objectSpread({}, _this.state.content.data))
      });
    });
    (0, _defineProperty2.default)(_this, "onViewerLoad", function (selectedArchiveEntry) {
      return function () {
        (0, _analytics.fireAnalytics)((0, _zipEntryLoadSucceeded.createZipEntryLoadSucceededEvent)(_this.props.item, selectedArchiveEntry), _this.props.createAnalyticsEvent);
      };
    });
    (0, _defineProperty2.default)(_this, "onViewerError", function (primaryErrorReason, selectedArchiveEntry) {
      return function (error) {
        return error && (0, _errors.isMediaViewerError)(error) ? _this.onError(new _errors.ArchiveViewerError(primaryErrorReason, error.secondaryError, selectedArchiveEntry)) : _this.onError(new _errors.ArchiveViewerError(primaryErrorReason, error, selectedArchiveEntry));
      };
    });
    (0, _defineProperty2.default)(_this, "onSidebarLoaded", function () {
      _this.setState({
        content: _domain.Outcome.successful(_objectSpread(_objectSpread({}, _this.state.content.data), {}, {
          hasLoadedEntries: true
        }))
      });
      _this.props.onSuccess();
    });
    return _this;
  }
  (0, _inherits2.default)(ArchiveViewerBase, _BaseViewer);
  return (0, _createClass2.default)(ArchiveViewerBase, [{
    key: "init",
    value: function () {
      var _init = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3() {
        return _regenerator.default.wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              this.setState(this.initialState);
            case 1:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this);
      }));
      function init() {
        return _init.apply(this, arguments);
      }
      return init;
    }()
  }, {
    key: "initialState",
    get: function get() {
      return {
        content: _domain.Outcome.successful({
          src: '',
          name: '',
          isDirectory: true
        })
      };
    }
  }, {
    key: "release",
    value: function release() {
      var content = this.state.content;
      if (!content.data || !content.data.src) {
        return;
      }
      URL.revokeObjectURL(content.data.src);
    }
  }, {
    key: "renderSuccessful",
    value: function renderSuccessful(content) {
      var _this$props = this.props,
        item = _this$props.item,
        mediaClient = _this$props.mediaClient,
        collectionName = _this$props.collectionName;
      var selectedArchiveEntry = content.selectedArchiveEntry,
        hasLoadedEntries = content.hasLoadedEntries;
      var hasSelectedArchiveEntry = selectedArchiveEntry !== undefined;
      return /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveLayout, null, /*#__PURE__*/_react.default.createElement(_archiveSidebarRenderer.default, {
        selectedFileState: item,
        mediaClient: mediaClient,
        onSelectedArchiveEntryChange: this.onSelectedArchiveEntryChange,
        onHeaderClicked: this.onHeaderClicked,
        isArchiveEntryLoading: !hasSelectedArchiveEntry,
        collectionName: collectionName,
        onError: this.onError,
        onSuccess: this.onSidebarLoaded
      }), /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveViewerWrapper, null, !hasSelectedArchiveEntry && !hasLoadedEntries ? /*#__PURE__*/_react.default.createElement(_styleWrappers.ListWrapper, null, /*#__PURE__*/_react.default.createElement(_loading.Spinner, null)) : this.renderArchiveItemViewer(content)));
    }
  }, {
    key: "renderArchiveItemViewer",
    value: function renderArchiveItemViewer(content) {
      var _this$props2 = this.props,
        item = _this$props2.item,
        viewerOptions = _this$props2.viewerOptions;
      var src = content.src,
        name = content.name,
        isDirectory = content.isDirectory,
        error = content.error,
        selectedArchiveEntry = content.selectedArchiveEntry,
        codeViewerSrc = content.codeViewerSrc,
        isCodeMimeType = content.isCodeMimeType;
      if (error) {
        return this.renderPreviewError(error, selectedArchiveEntry);
      }
      if (!isDirectory && selectedArchiveEntry) {
        var _viewerOptions$custom;
        if (!name || !src) {
          return this.renderPreviewError(new _errors.ArchiveViewerError('archiveviewer-missing-name-src'), selectedArchiveEntry);
        }
        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: item,
            archiveFileItem: {
              name: name
            }
          });
        });
        if (customRenderer) {
          return /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveItemViewerWrapper, null, customRenderer.renderContent({
            fileItem: item,
            archiveFileItem: {
              name: name
            },
            getBinaryContent: function () {
              var _getBinaryContent = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee4() {
                return _regenerator.default.wrap(function _callee4$(_context4) {
                  while (1) switch (_context4.prev = _context4.next) {
                    case 0:
                      _context4.next = 2;
                      return fetch(src);
                    case 2:
                      return _context4.abrupt("return", _context4.sent.blob());
                    case 3:
                    case "end":
                      return _context4.stop();
                  }
                }, _callee4);
              }));
              function getBinaryContent() {
                return _getBinaryContent.apply(this, arguments);
              }
              return getBinaryContent;
            }(),
            onLoad: this.onViewerLoad(selectedArchiveEntry),
            onError: this.onViewerError('archiveviewer-customrenderer-onerror', selectedArchiveEntry)
          }));
        }
        var mediaType = (0, _utils.getMediaTypeFromFilename)(name);
        if (isCodeMimeType) {
          // Same code viewer logic as in Item-Viewer.tsx
          // Render error message if code file has size over 10MB.
          // Required by https://product-fabric.atlassian.net/browse/MEX-1788
          if ((selectedArchiveEntry === null || selectedArchiveEntry === void 0 ? void 0 : selectedArchiveEntry.size) > _itemViewer.MAX_FILE_SIZE_SUPPORTED_BY_CODEVIEWER) {
            return this.renderPreviewError(new _errors.ArchiveViewerError('archiveviewer-codeviewer-file-size-exceeds'), selectedArchiveEntry);
          }
          return /*#__PURE__*/_react.default.createElement(_codeViewerRenderer.CodeViewRenderer, {
            onSuccess: this.onViewerLoad(selectedArchiveEntry),
            onError: this.onViewerError('archiveviewer-codeviewer-onerror', selectedArchiveEntry),
            item: item,
            src: codeViewerSrc || '',
            language: (0, _codeViewer.getLanguageType)(name) || _util.DEFAULT_LANGUAGE
          });
        }
        switch (mediaType) {
          case 'image':
            return /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveItemViewerWrapper, null, /*#__PURE__*/_react.default.createElement(_interactiveImg.InteractiveImg, {
              src: src,
              alt: name,
              onLoad: this.onViewerLoad(selectedArchiveEntry),
              onError: this.onViewerError('archiveviewer-imageviewer-onerror', selectedArchiveEntry)
            }));
          case 'video':
            return /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveItemViewerWrapper, null, /*#__PURE__*/_react.default.createElement(_styleWrappers.CustomVideoPlayerWrapper, {
              "data-testid": "media-viewer-video-content"
            }, /*#__PURE__*/_react.default.createElement(_mediaUi.CustomMediaPlayer, {
              type: "video",
              isAutoPlay: false,
              src: src,
              onCanPlay: this.onViewerLoad(selectedArchiveEntry),
              onError: this.onViewerError('archiveviewer-videoviewer-onerror', selectedArchiveEntry)
            })));
          case 'audio':
            return /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveItemViewerWrapper, null, /*#__PURE__*/_react.default.createElement(_styleWrappers.AudioPlayer, {
              "data-testid": "media-viewer-audio-content"
            }, /*#__PURE__*/_react.default.createElement(_styleWrappers.DefaultCoverWrapper, null, /*#__PURE__*/_react.default.createElement(_audioMediaServicesAudio.default, {
              label: "cover",
              LEGACY_size: "xlarge",
              color: "currentColor"
              // eslint-disable-next-line @atlaskit/design-system/ensure-design-token-usage
              ,
              LEGACY_primaryColor: "#22272B"
              // eslint-disable-next-line @atlaskit/design-system/ensure-design-token-usage
              ,
              LEGACY_secondaryColor: "#9FADBC"
            })), /*#__PURE__*/_react.default.createElement(_styleWrappers.CustomAudioPlayerWrapper, null, /*#__PURE__*/_react.default.createElement(_mediaUi.CustomMediaPlayer, {
              type: "audio",
              isAutoPlay: false,
              src: src,
              onCanPlay: this.onViewerLoad(selectedArchiveEntry),
              onError: this.onViewerError('archiveviewer-audioviewer-onerror', selectedArchiveEntry)
            }))));
          case 'doc':
            return /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveItemViewerWrapper, null, /*#__PURE__*/_react.default.createElement(_pdfRenderer.PDFRenderer, {
              item: item,
              src: src,
              onSuccess: this.onViewerLoad(selectedArchiveEntry),
              onError: this.onViewerError('archiveviewer-docviewer-onerror', selectedArchiveEntry)
            }));
          case 'archive':
            //BMPT-388 - Add illustration here, currently empty viewer
            return /*#__PURE__*/_react.default.createElement(_styleWrappers2.ArchiveItemViewerWrapper, null);
          default:
            return this.renderPreviewError(new _errors.ArchiveViewerError('archiveviewer-unsupported'), selectedArchiveEntry);
        }
      }
    }
  }, {
    key: "renderPreviewError",
    value: function renderPreviewError(error, entry) {
      var _this$props3 = this.props,
        item = _this$props3.item,
        createAnalyticsEvent = _this$props3.createAnalyticsEvent;
      (0, _analytics.fireAnalytics)((0, _zipEntryLoadFailed.createZipEntryLoadFailedEvent)(item, error, entry), createAnalyticsEvent);
      return /*#__PURE__*/_react.default.createElement(_styleWrappers.ListWrapper, null, /*#__PURE__*/_react.default.createElement(_errorMessage.default, {
        fileId: item.id,
        fileState: item,
        error: error,
        supressAnalytics: true
      }, /*#__PURE__*/_react.default.createElement(_compiled.Text, null, /*#__PURE__*/_react.default.createElement(_reactIntlNext.FormattedMessage, _mediaUi.messages.try_downloading_file))));
    }
  }]);
}(_baseViewer.BaseViewer);
var ArchiveViewer = exports.ArchiveViewer = (0, _analyticsNext.withAnalyticsEvents)()(ArchiveViewerBase);