import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
import _regeneratorRuntime from "@babel/runtime/regenerator";
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(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; })(); }
import React from 'react';
import { isErrorFileState, request } from '@atlaskit/media-client';
import { Outcome } from '../../domain';
import { MediaViewerError } from '../../errors';
import { Spinner } from '../../loading';
import { BaseViewer } from '../base-viewer';
import { DEFAULT_LANGUAGE, normaliseLineBreaks } from './util';
import { getLanguageType, getExtension } from '@atlaskit/media-ui/codeViewer';
import { msgToText } from './msg-parser';
import { CodeRendererAdvanced } from './CodeRendererAdvanced/CodeRendererAdvanced';
import { fg } from '@atlaskit/platform-feature-flags';
var moduleLoader = function moduleLoader() {
  return import( /* webpackChunkName: "@atlaskit-internal_media-code-viewer" */'./codeViewerRenderer');
};
var componentLoader = function componentLoader() {
  return moduleLoader().then(function (module) {
    return module.CodeViewRenderer;
  });
};
export var CodeViewer = /*#__PURE__*/function (_BaseViewer) {
  function CodeViewer() {
    _classCallCheck(this, CodeViewer);
    return _callSuper(this, CodeViewer, arguments);
  }
  _inherits(CodeViewer, _BaseViewer);
  return _createClass(CodeViewer, [{
    key: "initialState",
    get: function get() {
      return {
        content: Outcome.pending()
      };
    }
  }, {
    key: "init",
    value: function () {
      var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _this$props, item, mediaClient, collectionName, onError, downloadUrl, response, ext, arrayBuffer, src, _src, codeViewerError;
        return _regeneratorRuntime.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 request(downloadUrl, {
                method: 'GET',
                endpoint: '/file/{fileId}/binary'
              });
            case 11:
              response = _context.sent;
              ext = 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 = msgToText(arrayBuffer); // email contents parsed successfully
              if (!(typeof src === 'string')) {
                _context.next = 23;
                break;
              }
              this.onMediaDisplayed();
              this.setState({
                content: Outcome.successful(normaliseLineBreaks(src))
              });
              _context.next = 24;
              break;
            case 23:
              throw new 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: Outcome.successful(normaliseLineBreaks(_src))
              });
            case 31:
              _context.next = 38;
              break;
            case 33:
              _context.prev = 33;
              _context.t0 = _context["catch"](5);
              codeViewerError = new MediaViewerError('codeviewer-fetch-src', _context.t0 instanceof Error ? _context.t0 : undefined);
              this.setState({
                content: 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 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        return _regeneratorRuntime.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 (!isErrorFileState(item)) {
        return getLanguageType(item.name, item.mimeType);
      }
      return 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.createElement(Spinner, null);
      }
      if (fg('media_advanced_text_viewer')) {
        return /*#__PURE__*/React.createElement(CodeRendererAdvanced, {
          item: item,
          src: content,
          onSuccess: onSuccess,
          onError: onError,
          onClose: onClose
        });
      }
      return /*#__PURE__*/React.createElement(CodeViewerComponent, {
        item: item,
        src: content,
        language: this.getCodeLanguage(this.props.item) || DEFAULT_LANGUAGE,
        onSuccess: onSuccess,
        onError: onError,
        onClose: onClose
      });
    }
  }]);
}(BaseViewer);