"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _typeof = require("@babel/runtime/helpers/typeof");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.SvgViewer = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = _interopRequireWildcard(require("react"));
var _mediaUi = require("@atlaskit/media-ui");
var _mediaCommon = require("@atlaskit/media-common");
var _analyticsNext = require("@atlaskit/analytics-next");
var _styleWrappers = require("../../styleWrappers");
var _zoomLevel = require("../../domain/zoomLevel");
var _zoomControls = require("../../zoomControls");
var _closed = require("../../analytics/events/ui/closed");
var _mediaSvg = _interopRequireDefault(require("@atlaskit/media-svg"));
var _errors = require("../../errors");
var _utils = require("./utils");
var _ImageWrapper = require("./ImageWrapper");
var _errors2 = require("./errors");
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 SvgViewerBase = function SvgViewerBase(_ref) {
  var identifier = _ref.identifier,
    onLoad = _ref.onLoad,
    onClose = _ref.onClose,
    onBlanketClicked = _ref.onBlanketClicked,
    onError = _ref.onError;
  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)(false),
    _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
    isDragging = _useState4[0],
    setIsDragging = _useState4[1];
  var _useState5 = (0, _react.useState)(new _mediaUi.Vector2(0, 0)),
    _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
    cursorPos = _useState6[0],
    setCursorPos = _useState6[1];
  var _useState7 = (0, _react.useState)(),
    _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
    camera = _useState8[0],
    setCamera = _useState8[1];
  var wrapperRef = (0, _react.useRef)(null);
  var _useState9 = (0, _react.useState)(),
    _useState0 = (0, _slicedToArray2.default)(_useState9, 2),
    wrapperScroll = _useState0[0],
    setWrapperScroll = _useState0[1];
  var onResize = (0, _react.useCallback)(function () {
    if (!wrapperRef.current || !camera) {
      return;
    }
    var newViewport = (0, _utils.clientRectangle)(wrapperRef.current);
    var newCamera = camera.resizedViewport(newViewport);
    var newZoomLevel = (0, _utils.zoomLevelAfterResize)(newCamera, camera, zoomLevel);
    setCamera(newCamera);
    setZoomLevel(newZoomLevel);
  }, [camera, zoomLevel]);
  var panImage = (0, _react.useCallback)(function (ev) {
    if (isDragging && wrapperRef.current) {
      var newCursorPos = new _mediaUi.Vector2(ev.screenX, ev.screenY);
      var delta = cursorPos.sub(newCursorPos);
      setCursorPos(newCursorPos);
      wrapperRef.current.scrollLeft += delta.x;
      wrapperRef.current.scrollTop += delta.y;
    }
  }, [cursorPos, isDragging]);
  var stopDragging = (0, _react.useCallback)(function (ev) {
    ev.preventDefault();
    setIsDragging(false);
  }, []);
  (0, _react.useEffect)(function () {
    window.addEventListener('resize', onResize);
    document.addEventListener('mousemove', panImage);
    document.addEventListener('mouseup', stopDragging);
    return function () {
      window.removeEventListener('resize', onResize);
      document.removeEventListener('mousemove', panImage);
      document.removeEventListener('mouseup', stopDragging);
    };
  }, [onResize, panImage, stopDragging]);
  var onSvgLoad = function onSvgLoad(ev) {
    onLoad === null || onLoad === void 0 || onLoad();
    if (!wrapperRef.current) {
      return;
    }
    var viewport = (0, _utils.clientRectangle)(wrapperRef.current);
    var originalImgRect = (0, _utils.naturalSizeRectangle)(ev.currentTarget);
    var newCamera = new _mediaUi.Camera(viewport, originalImgRect);
    var newZoomLevel = new _zoomLevel.ZoomLevel(newCamera.scaleDownToFit);
    setCamera(newCamera);
    setZoomLevel(newZoomLevel);
  };
  var onSvgError = function onSvgError(err) {
    var error = new _errors.MediaViewerError((0, _errors2.getErrorReason)(err.primaryReason), err.secondaryError);
    onError(error);
  };
  var onSvgClicked = function onSvgClicked(e) {
    if (e.target === e.currentTarget) {
      onBlanketClicked === null || onBlanketClicked === void 0 || onBlanketClicked();
      onClose === null || onClose === void 0 || onClose();
    }
  };
  var startDragging = function startDragging(ev) {
    // stopping propagation to prevent media viewer from closing
    // when clicking on the image
    ev.stopPropagation();
    ev.preventDefault();
    setIsDragging(true);
    setCursorPos(new _mediaUi.Vector2(ev.screenX, ev.screenY));
  };
  var onZoomChange = function onZoomChange(nextZoomLevel) {
    var wrapper = wrapperRef.current;
    if (!wrapper || !camera) {
      return;
    }
    var scrollLeft = wrapper.scrollLeft,
      scrollTop = wrapper.scrollTop;
    var prevOffset = new _mediaUi.Vector2(scrollLeft, scrollTop);
    var prevZoomLevel = zoomLevel;
    setZoomLevel(nextZoomLevel);
    var _camera$scaledOffset = camera.scaledOffset(prevOffset, prevZoomLevel.value, nextZoomLevel.value),
      x = _camera$scaledOffset.x,
      y = _camera$scaledOffset.y;
    setWrapperScroll({
      scrollLeft: x,
      scrollTop: y
    });
  };
  (0, _react.useLayoutEffect)(function () {
    // Must scroll after the new zoom (onZoomChange) and before the repaint
    var wrapper = wrapperRef.current;
    if (!wrapper || !wrapperScroll) {
      return;
    }
    var scrollLeft = wrapperScroll.scrollLeft,
      scrollTop = wrapperScroll.scrollTop;
    wrapper.scrollLeft = scrollLeft;
    wrapper.scrollTop = scrollTop;
  }, [wrapperScroll]);

  // We use style attr instead of SC prop for perf reasons
  // When image loads it does two things at the same time 1) it renders itself in the browser 2) triggers onLoad
  // visibility: 'hidden' is here to prevent image rendering on the screen (with 100%) before next
  // react re-render when we have `camera` and can control it's zoom level.
  // overflow: 'hidden' is here to prevent scroll going wild while image is rendered in visibility: 'hidden'
  // We can't use display: none or not render image, because we do need `onLoad` to trigger and read it's dimensions

  var canDrag = camera && zoomLevel.value > camera.scaleToFit || false;
  var isHidden = !camera;
  var imgStyles = {
    visibility: isHidden ? 'hidden' : 'visible',
    cursor: canDrag && isDragging ? 'grabbing' : canDrag ? 'grab' : 'initial',
    display: 'inline-block',
    verticalAlign: 'middle',
    position: 'relative'
  };
  var imgDimensions = camera === null || camera === void 0 ? void 0 : camera.scaledImg(zoomLevel.value);
  return /*#__PURE__*/_react.default.createElement(_ImageWrapper.ImageWrapper, {
    onClick: onSvgClicked,
    ref: wrapperRef,
    isHidden: isHidden
  }, /*#__PURE__*/_react.default.createElement(_mediaSvg.default, {
    testId: 'media-viewer-svg',
    identifier: identifier,
    dimensions: imgDimensions
    // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
    ,
    style: imgStyles,
    onLoad: onSvgLoad,
    onMouseDown: startDragging,
    onError: onSvgError
  }), /*#__PURE__*/_react.default.createElement(_styleWrappers.BaselineExtend, null), /*#__PURE__*/_react.default.createElement(_zoomControls.ZoomControls, {
    zoomLevel: zoomLevel,
    onChange: onZoomChange
  }));
};
var SvgViewer = exports.SvgViewer = (0, _analyticsNext.withAnalyticsEvents)({
  onBlanketClicked: function onBlanketClicked(createAnalyticsEvent) {
    var event = createAnalyticsEvent((0, _closed.createClosedEvent)('blanket'));
    event.fire(_mediaCommon.ANALYTICS_MEDIA_CHANNEL);
  }
})(SvgViewerBase);