"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.InteractiveImgComponent = exports.InteractiveImg = void 0;
exports.zoomLevelAfterResize = zoomLevelAfterResize;
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 _react = _interopRequireDefault(require("react"));
var _mediaUi = require("@atlaskit/media-ui");
var _mediaCommon = require("@atlaskit/media-common");
var _constants = require("@atlaskit/media-client/constants");
var _analyticsNext = require("@atlaskit/analytics-next");
var _videoHd = _interopRequireDefault(require("@atlaskit/icon-lab/core/video-hd"));
var _videoHdFilled = _interopRequireDefault(require("@atlaskit/icon-lab/core/video-hd-filled"));
var _spinner = _interopRequireDefault(require("@atlaskit/spinner"));
var _styleWrappers = require("../../styleWrappers");
var _zoomLevel = require("../../domain/zoomLevel");
var _closeOnDirectClick = require("../../utils/closeOnDirectClick");
var _zoomControls = require("../../zoomControls");
var _closed = require("../../analytics/events/ui/closed");
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 zoomLevelAfterResize(newCamera, oldCamera, oldZoomLevel) {
  var isImgScaledToFit = oldZoomLevel.value === oldCamera.scaleDownToFit;
  var zoomLevelToRefit = new _zoomLevel.ZoomLevel(newCamera.scaleDownToFit);
  return isImgScaledToFit ? zoomLevelToRefit : oldZoomLevel;
}
var clientRectangle = function clientRectangle(el) {
  var clientWidth = el.clientWidth,
    clientHeight = el.clientHeight;
  return new _mediaUi.Rectangle(clientWidth, clientHeight);
};
var naturalSizeRectangle = function naturalSizeRectangle(el) {
  var naturalWidth = el.naturalWidth,
    naturalHeight = el.naturalHeight;
  return new _mediaUi.Rectangle(naturalWidth, naturalHeight);
};
var initialState = {
  zoomLevel: new _zoomLevel.ZoomLevel(1),
  isHDActive: false,
  isHDActivating: false,
  isHDAvailable: false,
  isDragging: false,
  cursorPos: new _mediaUi.Vector2(0, 0),
  hasBeenLoadedOnce: false
};
var InteractiveImgComponent = exports.InteractiveImgComponent = /*#__PURE__*/function (_React$Component) {
  function InteractiveImgComponent() {
    var _this;
    (0, _classCallCheck2.default)(this, InteractiveImgComponent);
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _callSuper(this, InteractiveImgComponent, [].concat(args));
    (0, _defineProperty2.default)(_this, "state", initialState);
    (0, _defineProperty2.default)(_this, "saveWrapperRef", function (ref) {
      return _this.wrapper = ref;
    });
    (0, _defineProperty2.default)(_this, "onImageClicked", function (e) {
      var _this$props = _this.props,
        onClose = _this$props.onClose,
        onBlanketClicked = _this$props.onBlanketClicked;
      if (e.target === e.currentTarget && onBlanketClicked) {
        onBlanketClicked();
      }
      (0, _closeOnDirectClick.closeOnDirectClick)(onClose)(e);
    });
    (0, _defineProperty2.default)(_this, "onImgLoad", function (ev) {
      var _this$props2 = _this.props,
        onLoad = _this$props2.onLoad,
        originalBinaryImageSrc = _this$props2.originalBinaryImageSrc;
      var _this$state = _this.state,
        hasBeenLoadedOnce = _this$state.hasBeenLoadedOnce,
        oldZoomLevel = _this$state.zoomLevel,
        currentCamera = _this$state.camera;
      var _this$state2 = _this.state,
        isHDActivating = _this$state2.isHDActivating,
        isHDAvailable = _this$state2.isHDAvailable,
        isHDActive = _this$state2.isHDActive;
      if (!_this.wrapper) {
        return;
      }
      var viewport = clientRectangle(_this.wrapper);
      var originalImgRect = naturalSizeRectangle(ev.currentTarget);
      var camera = new _mediaUi.Camera(viewport, originalImgRect);
      var newZoomLevel;
      if (hasBeenLoadedOnce && currentCamera) {
        /* This is not first time image is loading. Likely due to new (HD) image is loaded.
         * In order to keep new image on the same perceived zoom level we need to scale.
         * It depends on ration between old and new images and current zoom level.
         * For example:
         * - old image is 2000px with zoom at 50% (0.5). New image is 4000px. 2000/4000 * 0.5 = 0.25 (25%)
         * - old image is 2000px with zoom at 200% (2). New image is 4000px. 2000/4000 * 2 = 1 (100%)
         */
        var previousImageWidth = currentCamera.originalImg.width;
        var newImageWidth = originalImgRect.width;
        newZoomLevel = new _zoomLevel.ZoomLevel(previousImageWidth / newImageWidth * oldZoomLevel.value);
        isHDActivating = false;
      } else {
        newZoomLevel = new _zoomLevel.ZoomLevel(camera.scaleDownToFit);

        // If initial (non-HD) image is equal to MAX resolution -
        // this means most likely original image had higher res (because non-HD is downsized and caped off with MAX res)
        isHDAvailable = !!originalBinaryImageSrc && (originalImgRect.width === _constants.MAX_RESOLUTION || originalImgRect.height === _constants.MAX_RESOLUTION);

        // Automatically activate HD on first load if zoom level is already 100% or bigger
        isHDActive = newZoomLevel.value >= 1;
        if (onLoad) {
          // Call onLoad only once on initial image render
          onLoad();
        }
      }
      _this.setState({
        camera: camera,
        zoomLevel: newZoomLevel,
        hasBeenLoadedOnce: true,
        isHDActivating: isHDActivating,
        isHDAvailable: isHDAvailable,
        isHDActive: isHDActive
      });
    });
    (0, _defineProperty2.default)(_this, "onResize", function () {
      var camera = _this.state.camera;
      if (!_this.wrapper || !camera) {
        return;
      }
      var oldZoomLevel = _this.state.zoomLevel;
      var newViewport = clientRectangle(_this.wrapper);
      var newCamera = camera.resizedViewport(newViewport);
      var newZoomLevel = zoomLevelAfterResize(newCamera, camera, oldZoomLevel);
      _this.setState({
        camera: newCamera,
        zoomLevel: newZoomLevel
      });
    });
    (0, _defineProperty2.default)(_this, "onZoomChange", function (nextZoomLevel) {
      var camera = _this.state.camera;
      var _this2 = _this,
        wrapper = _this2.wrapper;
      if (!wrapper || !camera) {
        return;
      }
      var scrollLeft = wrapper.scrollLeft,
        scrollTop = wrapper.scrollTop;
      var prevOffset = new _mediaUi.Vector2(scrollLeft, scrollTop);
      var _this$state3 = _this.state,
        prevZoomLevel = _this$state3.zoomLevel,
        prevIsHDActive = _this$state3.isHDActive,
        prevIsHDActivating = _this$state3.isHDActivating;
      var isHDActive = prevIsHDActive || nextZoomLevel.value >= 1;
      var isHDActivating = prevIsHDActivating || !prevIsHDActive && isHDActive;
      _this.setState({
        zoomLevel: nextZoomLevel,
        isHDActive: isHDActive,
        isHDActivating: isHDActivating
      }, function () {
        var _camera$scaledOffset = camera.scaledOffset(prevOffset, prevZoomLevel.value, nextZoomLevel.value),
          x = _camera$scaledOffset.x,
          y = _camera$scaledOffset.y;
        wrapper.scrollLeft = x;
        wrapper.scrollTop = y;
      });
    });
    (0, _defineProperty2.default)(_this, "startDragging", function (ev) {
      // stopping propagation to prevent media viewer from closing
      // when clicking on the image
      ev.stopPropagation();
      ev.preventDefault();
      _this.setState({
        isDragging: true,
        cursorPos: new _mediaUi.Vector2(ev.screenX, ev.screenY)
      });
    });
    (0, _defineProperty2.default)(_this, "stopDragging", function (ev) {
      ev.preventDefault();
      _this.setState({
        isDragging: false
      });
    });
    (0, _defineProperty2.default)(_this, "panImage", function (ev) {
      if (_this.state.isDragging && _this.wrapper) {
        var cursorPos = new _mediaUi.Vector2(ev.screenX, ev.screenY);
        var delta = _this.state.cursorPos.sub(cursorPos);
        _this.setState({
          cursorPos: cursorPos
        });
        _this.wrapper.scrollLeft += delta.x;
        _this.wrapper.scrollTop += delta.y;
      }
    });
    return _this;
  }
  (0, _inherits2.default)(InteractiveImgComponent, _React$Component);
  return (0, _createClass2.default)(InteractiveImgComponent, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.state = initialState;
      window.addEventListener('resize', this.onResize);
      document.addEventListener('mousemove', this.panImage);
      document.addEventListener('mouseup', this.stopDragging);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      window.removeEventListener('resize', this.onResize);
      document.removeEventListener('mousemove', this.panImage);
      document.removeEventListener('mouseup', this.stopDragging);
    }
  }, {
    key: "renderHDIndicator",
    value: function renderHDIndicator() {
      var _this$state4 = this.state,
        isHDActivating = _this$state4.isHDActivating,
        isHDAvailable = _this$state4.isHDAvailable,
        isHDActive = _this$state4.isHDActive;
      if (!isHDAvailable) {
        return null;
      }
      return (
        /*#__PURE__*/
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
        _react.default.createElement(_styleWrappers.HDIconGroupWrapper, {
          className: _mediaUi.hideControlsClassName
        }, isHDActivating ? /*#__PURE__*/_react.default.createElement(_spinner.default, {
          appearance: "invert"
        }) : undefined, isHDActive ? /*#__PURE__*/_react.default.createElement(_videoHdFilled.default, {
          label: "hd active"
        }) : /*#__PURE__*/_react.default.createElement(_videoHd.default, {
          label: "hd"
        }))
      );
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
        src = _this$props3.src,
        originalBinaryImageSrc = _this$props3.originalBinaryImageSrc,
        orientation = _this$props3.orientation,
        onError = _this$props3.onError;
      var _this$state5 = this.state,
        zoomLevel = _this$state5.zoomLevel,
        isHDAvailable = _this$state5.isHDAvailable,
        isHDActive = _this$state5.isHDActive,
        camera = _this$state5.camera,
        isDragging = _this$state5.isDragging;
      var canDrag = camera && zoomLevel.value > camera.scaleToFit || false;
      // We use style attr instead of SC prop for perf reasons
      // @ts-ignore
      var imgStyle = camera && camera.scaledImg(zoomLevel.value) || {
        visibility: 'hidden'
      };
      // 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 wrapperStyleOverride = camera ? {} : {
        overflow: 'hidden'
      };
      if (orientation) {
        imgStyle.transform = (0, _mediaUi.getCssFromImageOrientation)(orientation);
      }
      var srcToDisplay = isHDAvailable && isHDActive && originalBinaryImageSrc ? originalBinaryImageSrc : src;
      return /*#__PURE__*/_react.default.createElement(_styleWrappers.ImageWrapper, {
        "data-testid": "media-viewer-image-content",
        onClick: this.onImageClicked,
        ref: this.saveWrapperRef
        // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
        ,
        style: wrapperStyleOverride
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
        ,
        className: "media-viewer-image-content"
      }, /*#__PURE__*/_react.default.createElement(_styleWrappers.Img, {
        "data-testid": "media-viewer-image",
        canDrag: canDrag,
        isDragging: isDragging,
        src: srcToDisplay,
        alt: this.props.alt
        // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop -- Ignored via go/DSP-18766
        ,
        style: imgStyle,
        onLoad: this.onImgLoad,
        onError: onError,
        onMouseDown: this.startDragging,
        shouldPixelate: zoomLevel.value > 1
        // eslint-disable-next-line @atlaskit/ui-styling-standard/no-classname-prop -- Ignored via go/DSP-18766
        ,
        className: "media-viewer-image"
      }), /*#__PURE__*/_react.default.createElement(_styleWrappers.BaselineExtend, null), /*#__PURE__*/_react.default.createElement(_zoomControls.ZoomControls, {
        zoomLevel: zoomLevel,
        onChange: this.onZoomChange
      }, this.renderHDIndicator()));
    }
  }]);
}(_react.default.Component);
var InteractiveImg = exports.InteractiveImg = (0, _analyticsNext.withAnalyticsEvents)({
  onBlanketClicked: function onBlanketClicked(createAnalyticsEvent) {
    var event = createAnalyticsEvent((0, _closed.createClosedEvent)('blanket'));
    event.fire(_mediaCommon.ANALYTICS_MEDIA_CHANNEL);
  }
})(InteractiveImgComponent);