import { set, unset } from "../../util/Cursor.mjs";
import { install } from "../../util/ClickTrap.mjs";
import { delta } from "../../util/PositionUtil.mjs";
import { closest, event } from "../../../../min-dom/dist/index.esm.mjs";
import { toPoint } from "../../util/Event.mjs";
var THRESHOLD = 15;
function MoveCanvas(eventBus, canvas) {
  var context;
  eventBus.on("element.mousedown", 500, function(e) {
    return handleStart(e.originalEvent);
  });
  function handleMove(event2) {
    var start = context.start, button = context.button, position = toPoint(event2), delta$1 = delta(position, start);
    if (!context.dragging && length(delta$1) > THRESHOLD) {
      context.dragging = true;
      if (button === 0) {
        install(eventBus);
      }
      set("grab");
    }
    if (context.dragging) {
      var lastPosition = context.last || context.start;
      delta$1 = delta(position, lastPosition);
      canvas.scroll({
        dx: delta$1.x,
        dy: delta$1.y
      });
      context.last = position;
    }
    event2.preventDefault();
  }
  function handleEnd(event$1) {
    event.unbind(document, "mousemove", handleMove);
    event.unbind(document, "mouseup", handleEnd);
    context = null;
    unset();
  }
  function handleStart(event$1) {
    if (closest(event$1.target, ".djs-draggable")) {
      return;
    }
    var button = event$1.button;
    if (button >= 2 || event$1.ctrlKey || event$1.shiftKey || event$1.altKey) {
      return;
    }
    context = {
      button,
      start: toPoint(event$1)
    };
    event.bind(document, "mousemove", handleMove);
    event.bind(document, "mouseup", handleEnd);
    return true;
  }
  this.isActive = function() {
    return !!context;
  };
}
MoveCanvas.$inject = [
  "eventBus",
  "canvas"
];
function length(point) {
  return Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
}
export {
  MoveCanvas as default
};
