package org.hirw.game;

import static org.lwjgl.glfw.GLFW.*;

import java.util.HashMap;

public class Mouse {
  private double x, y, oldX, oldY;
  private HashMap<Integer, Boolean> buttons;

  private static Mouse instance;

  public interface Buttons {
    public final int LEFT = GLFW_MOUSE_BUTTON_LEFT;
    public final int RIGHT = GLFW_MOUSE_BUTTON_RIGHT;
  }

  private Mouse() {
    this.buttons = new HashMap<Integer, Boolean>();
  }

  public static Mouse getInstance() {
    if (instance == null) {
      synchronized (Mouse.class) { // Double checked locking
        if (instance == null) {
          instance = new Mouse();
        }
      }
    }
    return instance;
  }

  public static void cursorPositionCallback(long window, double newX, double newY) {
    getInstance().oldX = getInstance().x;
    getInstance().oldY = getInstance().y;
    getInstance().x = newX;
    getInstance().y = newY;
  }

  public static void mouseButtonCallback(long window, int keyCode, int action, int _modifiers) {
    if (action == GLFW_PRESS) {
      getInstance().buttons.put(keyCode, true);
    } else if (action == GLFW_RELEASE) {
      getInstance().buttons.put(keyCode, false);
    }
  }

  public static double getX() {
    return getInstance().x;
  }

  public static double getY() {
    return getInstance().y;
  }

  public static double getDeltaX() {
    return getInstance().oldX - getInstance().x;
  }

  public static double getDeltaY() {
    return getInstance().oldY - getInstance().y;
  }

  public static boolean isPressed(int keyCode) {
    return getInstance().buttons.getOrDefault(keyCode, false);
  }
}
