"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.pdfViewerClassName = exports.PDFRenderer = void 0;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
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 _react = _interopRequireWildcard(require("react"));
var _pdf_viewer = require("pdfjs-dist/legacy/web/pdf_viewer");
var _pdf = require("pdfjs-dist/legacy/build/pdf");
var _analyticsNext = require("@atlaskit/analytics-next");
var _cmaps = require("./cmaps");
var _zoomControls = require("../../zoomControls");
var _styleWrappers = require("../../styleWrappers");
var _closeOnDirectClick = require("../../utils/closeOnDirectClick");
var _domain = require("../../domain");
var _loading = require("../../loading");
var _errorMessage = _interopRequireDefault(require("../../errorMessage"));
var _zoomLevel = require("../../domain/zoomLevel");
var _processError = require("./processError");
var _pdfJs = require("./pdfJs");
var _extractCompressedBase = require("./extractCompressedBase64");
var _pdfPasswordInput = require("./pdfPasswordInput");
var _analytics = require("../../analytics");
var _pdfPasswordInput2 = require("../../analytics/events/screen/pdfPasswordInput");
var _passwordPdf = require("../../analytics/events/screen/passwordPdf");
var _pdfRendererWrapper = require("./pdfRendererWrapper");
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" != _typeof(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 pdfViewerClassName = exports.pdfViewerClassName = 'pdfViewer';
var CmapFactory = /*#__PURE__*/function () {
  function CmapFactory() {
    (0, _classCallCheck2.default)(this, CmapFactory);
  }
  return (0, _createClass2.default)(CmapFactory, [{
    key: "fetch",
    value: function () {
      var _fetch = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee(_ref) {
        var name, module, data;
        return _regenerator.default.wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              name = _ref.name;
              _context.next = 3;
              return _cmaps.cmap[name]();
            case 3:
              module = _context.sent;
              _context.next = 6;
              return (0, _extractCompressedBase.extractCompressedBase64)(module.default);
            case 6:
              data = _context.sent;
              return _context.abrupt("return", {
                cMapData: data,
                compressionType: _pdf.CMapCompressionType.BINARY
              });
            case 8:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      function fetch(_x) {
        return _fetch.apply(this, arguments);
      }
      return fetch;
    }()
  }]);
}();
var defaultWorkerUrl = '';
var PDFRendererBase = function PDFRendererBase(_ref2) {
  var src = _ref2.src,
    onClose = _ref2.onClose,
    onSuccess = _ref2.onSuccess,
    onError = _ref2.onError,
    workerUrl = _ref2.workerUrl,
    item = _ref2.item,
    createAnalyticsEvent = _ref2.createAnalyticsEvent;
  var _useState = (0, _react.useState)(new _zoomLevel.ZoomLevel(1)),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    zoomLevel = _useState2[0],
    setZoomLevel = _useState2[1];
  var _useState3 = (0, _react.useState)(_domain.Outcome.pending()),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    docOutcome = _useState4[0],
    setDocOutcome = _useState4[1];
  var isPasswordPdfRef = (0, _react.useRef)(false);
  var _useState5 = (0, _react.useState)(false),
    _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
    passwordProtected = _useState6[0],
    setPasswordProtected = _useState6[1];
  var _useState7 = (0, _react.useState)(false),
    _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
    hasPasswordError = _useState8[0],
    setHasPasswordError = _useState8[1];
  var pdfWrapperRef = (0, _react.useRef)();
  var docRef = (0, _react.useRef)();
  var pdfViewerRef = (0, _react.useRef)();
  var onSuccessRef = (0, _react.useRef)(onSuccess);
  onSuccessRef.current = onSuccess;
  var updatePasswordRef = (0, _react.useRef)(undefined);
  var onErrorRef = (0, _react.useRef)(onError);
  onErrorRef.current = onError;
  var existingGlobalWorkerRef = (0, _react.useRef)(undefined);
  (0, _react.useEffect)(function () {
    /**
     * CXP-4622: Fixes issue of PDF.js reusing the global worker registered by embeded PDF macro in confluence
     * The global worker will likely be a different version and thus throw an error.
     * This will remove the worker on mount and will re-register it on unmount
     */
    var _ref3 = window,
      pdfjsWorker = _ref3.pdfjsWorker;
    if (pdfjsWorker) {
      existingGlobalWorkerRef.current = pdfjsWorker;
      window.pdfjsWorker = undefined;
    }
    var isSubscribed = true;
    var fetchDoc = /*#__PURE__*/function () {
      var _ref4 = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2() {
        var blob, getDocumentTask, pdfError;
        return _regenerator.default.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.prev = 0;
              if (!(!workerUrl && !defaultWorkerUrl)) {
                _context2.next = 6;
                break;
              }
              _context2.next = 4;
              return (0, _extractCompressedBase.extractCompressedBase64)(_pdfJs.pdfJs, 'blob');
            case 4:
              blob = _context2.sent;
              defaultWorkerUrl = URL.createObjectURL(blob);
            case 6:
              _pdf.GlobalWorkerOptions.workerSrc = workerUrl !== null && workerUrl !== void 0 ? workerUrl : defaultWorkerUrl;
              getDocumentTask = (0, _pdf.getDocument)({
                url: src,
                CMapReaderFactory: CmapFactory,
                isEvalSupported: false
              });
              getDocumentTask.onPassword = function (updatePassword, e) {
                updatePasswordRef.current = updatePassword;
                if (e === _pdf.PasswordResponses.NEED_PASSWORD) {
                  isPasswordPdfRef.current = true;
                  setPasswordProtected(true);
                } else {
                  setHasPasswordError(true);
                }
              };
              _context2.next = 11;
              return getDocumentTask.promise;
            case 11:
              docRef.current = _context2.sent;
              isSubscribed && setDocOutcome(_domain.Outcome.successful(docRef.current));
              _context2.next = 20;
              break;
            case 15:
              _context2.prev = 15;
              _context2.t0 = _context2["catch"](0);
              pdfError = (0, _processError.processError)(_context2.t0);
              isSubscribed && setDocOutcome(_domain.Outcome.failed(pdfError));
              if (onErrorRef.current) {
                onErrorRef.current(pdfError);
              }
            case 20:
            case "end":
              return _context2.stop();
          }
        }, _callee2, null, [[0, 15]]);
      }));
      return function fetchDoc() {
        return _ref4.apply(this, arguments);
      };
    }();
    fetchDoc();
    return function () {
      isSubscribed = false;
      if (docRef.current) {
        docRef.current.destroy();
      }
      window.pdfjsWorker = existingGlobalWorkerRef.current;
    };
  }, [src, workerUrl]);
  (0, _react.useEffect)(function () {
    if (docOutcome.status !== 'SUCCESSFUL' || !pdfWrapperRef.current) {
      return;
    }
    var eventBus = new _pdf_viewer.EventBus();
    var pdfLinkService = new _pdf_viewer.PDFLinkService({
      eventBus: eventBus
    });
    pdfViewerRef.current = new _pdf_viewer.PDFViewer({
      container: pdfWrapperRef.current,
      eventBus: eventBus,
      linkService: pdfLinkService,
      l10n: _pdf_viewer.NullL10n
    });
    pdfLinkService.setViewer(pdfViewerRef.current);
    pdfViewerRef.current.setDocument(docRef.current);
    pdfLinkService.setDocument(docRef.current, null);
    pdfViewerRef.current.firstPagePromise.then(scaleToFit);
    if (isPasswordPdfRef.current) {
      (0, _analytics.fireAnalytics)((0, _passwordPdf.createPasswordPdfScreenEvent)(), createAnalyticsEvent);
    }
    if (onSuccessRef.current) {
      onSuccessRef.current();
    }
  }, [createAnalyticsEvent, docOutcome.status]);
  var savePdfElement = function savePdfElement(el) {
    pdfWrapperRef.current = el;
  };
  var handleZoom = function handleZoom(zoomLevel) {
    pdfViewerRef.current.currentScale = zoomLevel.value;
    setZoomLevel(zoomLevel);
  };
  var scaleToFit = function scaleToFit() {
    if (pdfViewerRef.current) {
      pdfViewerRef.current.currentScaleValue = 'page-width';
      setZoomLevel(new _zoomLevel.ZoomLevel(pdfViewerRef.current.currentScale));
    }
  };
  return docOutcome.match({
    pending: function pending() {
      return passwordProtected ? /*#__PURE__*/_react.default.createElement(_pdfPasswordInput.PDFPasswordInput, {
        onRender: function onRender() {
          return (0, _analytics.fireAnalytics)((0, _pdfPasswordInput2.createPdfPasswordInputScreenEvent)(), createAnalyticsEvent);
        },
        onSubmit: function onSubmit(data) {
          var _updatePasswordRef$cu;
          // Reset hasPasswordError on each submission
          hasPasswordError && setHasPasswordError(false);
          (_updatePasswordRef$cu = updatePasswordRef.current) === null || _updatePasswordRef$cu === void 0 || _updatePasswordRef$cu.call(updatePasswordRef, data.password);
        },
        hasPasswordError: hasPasswordError
      }) : /*#__PURE__*/_react.default.createElement(_loading.Spinner, null);
    },
    successful: function successful() {
      return /*#__PURE__*/_react.default.createElement(_pdfRendererWrapper.PDFRendererWrapper, null, /*#__PURE__*/_react.default.createElement(_styleWrappers.PDFWrapper, {
        "data-testid": "media-viewer-pdf-content",
        ref: savePdfElement
      },
      /*#__PURE__*/
      // eslint-disable-next-line @atlaskit/design-system/prefer-primitives, @atlassian/a11y/click-events-have-key-events, @atlassian/a11y/interactive-element-not-keyboard-focusable, @atlassian/a11y/no-static-element-interactions
      _react.default.createElement("div", {
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
        className: pdfViewerClassName,
        onClick: (0, _closeOnDirectClick.closeOnDirectClick)(onClose)
      }), /*#__PURE__*/_react.default.createElement(_zoomControls.ZoomControls, {
        zoomLevel: zoomLevel,
        onChange: handleZoom
      })));
    },
    failed: function failed(error) {
      return /*#__PURE__*/_react.default.createElement(_errorMessage.default, {
        fileId: item.id,
        fileState: item,
        error: error,
        supressAnalytics: true // item-viewer.tsx will send
      });
    }
  });
};
var PDFRenderer = exports.PDFRenderer = (0, _analyticsNext.withAnalyticsEvents)()(PDFRendererBase);