"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.CodeViewer = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
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 _react = _interopRequireDefault(require("react"));
var _mediaClient = require("@atlaskit/media-client");
var _domain = require("../../domain");
var _errors = require("../../errors");
var _loading = require("../../loading");
var _baseViewer = require("../base-viewer");
var _util = require("./util");
var _codeViewer = require("@atlaskit/media-ui/codeViewer");
var _msgParser = require("./msg-parser");
var _CodeRendererAdvanced = require("./CodeRendererAdvanced/CodeRendererAdvanced");
var _platformFeatureFlags = require("@atlaskit/platform-feature-flags");
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 _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 moduleLoader = function moduleLoader() {
  return Promise.resolve().then(function () {
    return _interopRequireWildcard(require( /* webpackChunkName: "@atlaskit-internal_media-code-viewer" */'./codeViewerRenderer'));
  });
};
var componentLoader = function componentLoader() {
  return moduleLoader().then(function (module) {
    return module.CodeViewRenderer;
  });
};
var CodeViewer = exports.CodeViewer = /*#__PURE__*/function (_BaseViewer) {
  function CodeViewer() {
    (0, _classCallCheck2.default)(this, CodeViewer);
    return _callSuper(this, CodeViewer, arguments);
  }
  (0, _inherits2.default)(CodeViewer, _BaseViewer);
  return (0, _createClass2.default)(CodeViewer, [{
    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, item, mediaClient, collectionName, onError, downloadUrl, response, ext, arrayBuffer, src, _src, codeViewerError;
        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              if (CodeViewer.CodeViewerComponent) {
                _context.next = 3;
                break;
              }
              _context.next = 3;
              return this.loadCodeViewer();
            case 3:
              _this$props = this.props, item = _this$props.item, mediaClient = _this$props.mediaClient, collectionName = _this$props.collectionName, onError = _this$props.onError;
              if (!(item.status === 'processed' || item.status === 'processing')) {
                _context.next = 38;
                break;
              }
              _context.prev = 5;
              _context.next = 8;
              return mediaClient.file.getFileBinaryURL(item.id, collectionName);
            case 8:
              downloadUrl = _context.sent;
              _context.next = 11;
              return (0, _mediaClient.request)(downloadUrl, {
                method: 'GET',
                endpoint: '/file/{fileId}/binary'
              });
            case 11:
              response = _context.sent;
              ext = (0, _codeViewer.getExtension)(item.name); // Pass through EmailViewer logic
              if (!(ext === 'msg')) {
                _context.next = 26;
                break;
              }
              _context.next = 16;
              return response.arrayBuffer();
            case 16:
              arrayBuffer = _context.sent;
              src = (0, _msgParser.msgToText)(arrayBuffer); // email contents parsed successfully
              if (!(typeof src === 'string')) {
                _context.next = 23;
                break;
              }
              this.onMediaDisplayed();
              this.setState({
                content: _domain.Outcome.successful((0, _util.normaliseLineBreaks)(src))
              });
              _context.next = 24;
              break;
            case 23:
              throw new _errors.MediaViewerError('codeviewer-parse-email');
            case 24:
              _context.next = 31;
              break;
            case 26:
              _context.next = 28;
              return response.text();
            case 28:
              _src = _context.sent;
              this.onMediaDisplayed();
              this.setState({
                content: _domain.Outcome.successful((0, _util.normaliseLineBreaks)(_src))
              });
            case 31:
              _context.next = 38;
              break;
            case 33:
              _context.prev = 33;
              _context.t0 = _context["catch"](5);
              codeViewerError = new _errors.MediaViewerError('codeviewer-fetch-src', _context.t0 instanceof Error ? _context.t0 : undefined);
              this.setState({
                content: _domain.Outcome.failed(codeViewerError)
              });
              if (onError) {
                onError(codeViewerError);
              }
            case 38:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[5, 33]]);
      }));
      function init() {
        return _init.apply(this, arguments);
      }
      return init;
    }()
  }, {
    key: "loadCodeViewer",
    value: function () {
      var _loadCodeViewer = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2() {
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return componentLoader();
            case 2:
              CodeViewer.CodeViewerComponent = _context2.sent;
              this.forceUpdate();
            case 4:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function loadCodeViewer() {
        return _loadCodeViewer.apply(this, arguments);
      }
      return loadCodeViewer;
    }()
  }, {
    key: "getCodeLanguage",
    value: function getCodeLanguage(item) {
      if (!(0, _mediaClient.isErrorFileState)(item)) {
        return (0, _codeViewer.getLanguageType)(item.name, item.mimeType);
      }
      return _util.DEFAULT_LANGUAGE;
    }
  }, {
    key: "release",
    value: function release() {}
  }, {
    key: "renderSuccessful",
    value: function renderSuccessful(content) {
      var _this$props2 = this.props,
        item = _this$props2.item,
        onClose = _this$props2.onClose,
        onSuccess = _this$props2.onSuccess,
        onError = _this$props2.onError;
      var CodeViewerComponent = CodeViewer.CodeViewerComponent;
      if (!CodeViewerComponent) {
        return /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
      }
      if ((0, _platformFeatureFlags.fg)('media_advanced_text_viewer')) {
        return /*#__PURE__*/_react.default.createElement(_CodeRendererAdvanced.CodeRendererAdvanced, {
          item: item,
          src: content,
          onSuccess: onSuccess,
          onError: onError,
          onClose: onClose
        });
      }
      return /*#__PURE__*/_react.default.createElement(CodeViewerComponent, {
        item: item,
        src: content,
        language: this.getCodeLanguage(this.props.item) || _util.DEFAULT_LANGUAGE,
        onSuccess: onSuccess,
        onError: onError,
        onClose: onClose
      });
    }
  }]);
}(_baseViewer.BaseViewer);