/**
 * Management class for Mouse events.
 * @see {@link foundry.Game#mouse}
 */
export default class MouseManager {
  constructor() {
    if ( game.mouse ) throw new Error("You may not re-construct the singleton MouseManager instance.");
  }

  /* -------------------------------------------- */

  /**
   * Begin listening to mouse events.
   * @internal
   */
  _activateListeners() {
    window.addEventListener("wheel", this.#onWheel.bind(this), {passive: false});
  }

  /* -------------------------------------------- */

  /**
   * Master mouse-wheel event handler
   * @param {WheelEvent} event    The mouse wheel event
   */
  #onWheel(event) {

    // Prevent zooming the entire browser window
    if ( event.ctrlKey ) event.preventDefault();

    // Interpret shift+scroll as vertical scroll
    let dy = event.delta = event.deltaY;
    if ( event.shiftKey && (dy === 0) ) {
      dy = event.delta = event.deltaX;
    }
    if ( dy === 0 ) return;

    // Take no actions if the canvas is not hovered
    if ( !canvas.ready ) return;
    const hover = document.elementFromPoint(event.clientX, event.clientY);
    if ( !hover || (hover.id !== "board") ) return;
    event.preventDefault();

    // Identify scroll modifiers
    const isCtrl = game.keyboard.isModifierActive("CONTROL"); // We cannot trust event.ctrlKey because of touchpads
    const isShift = event.shiftKey;
    if ( isCtrl || isShift ) {

      // Case 1 - active ruler
      const ruler = canvas.controls.ruler;
      if ( ruler.active ) return ruler._onMouseWheel(event);

      // Case 2 - active layer
      return canvas.activeLayer._onMouseWheel(event);
    }

    // Case 3 - zoom the canvas
    canvas._onMouseWheel(event);
  }
}
