import { EndlessCanvas } from './EndlessCanvas';

export default (scene: EndlessCanvas) => {
  const DRAG_SENSITIVITY = 0.3;
  const dragStartPoint = { x: 0, y: 0 };
  let isDragging = false;

  const updateCursor = (cursorStyle) => {
    scene.input.setDefaultCursor(cursorStyle);
  };

  const startDragging = (pointer) => {
    dragStartPoint.x = pointer.x;
    dragStartPoint.y = pointer.y;
    if (!scene.isInputMode) {
      isDragging = true;
      updateCursor('grab');
    }
  };

  const stopDragging = () => {
    isDragging = false;
    updateCursor('default');
  };

  const handleDrag = (pointer) => {
    const { x, y } = pointer;
    const dragX = x - dragStartPoint.x;
    const dragY = y - dragStartPoint.y;
    scene.cameras.main.scrollX -= dragX;
    scene.cameras.main.scrollY -= dragY;
    dragStartPoint.x = x;
    dragStartPoint.y = y;
  };

  const handleWheel = (pointer, gameObjects, deltaX, deltaY) => {
    //@ts-ignore
    if (!scene.keys.ctrl.isDown) {
      scene.cameras.main.scrollX -= deltaX * DRAG_SENSITIVITY;
      scene.cameras.main.scrollY -= deltaY * DRAG_SENSITIVITY;
    }
  };
  //@ts-ignore
  scene.keys.space.on('down', () => {
    if (!scene.isInputMode) {
      updateCursor('grab');
    }
  });
  //@ts-ignore
  scene.keys.space.on('up', stopDragging);

  scene.input.on('pointerdown', (pointer) => {
    //@ts-ignore
    if (scene.keys.space.isDown && pointer.button === 0) startDragging(pointer);
  });

  scene.input.on('pointermove', (pointer) => {
    if (isDragging) handleDrag(pointer);
  });

  scene.input.on('pointerup', stopDragging);
  scene.input.on('wheel', handleWheel);
};
