import { WindowMouseEvent } from "https://deno.land/x/dwm@0.3.3/mod.ts";
import { gameWindow } from "./window.ts";

export const M = {
	NONE: -1,
	LEFT: 0,
	RIGHT: 1,
	MIDDLE: 2,
}

const mouseButtonsDown = {
	[M.LEFT]: false,
	[M.RIGHT]: false,
	[M.MIDDLE]: false,
};
const mouseEvents: Array<{
	type: "click" | "down" | "up" | "move" | "dblclick",
	button: typeof M[keyof typeof M],
	x: number,
	y: number,
	prevX?: number,
	prevY?: number
}> = [];

let mouseX = 0;
let mouseY = 0;

const eventPixelCoords = (evt: WindowMouseEvent) => {
	const {width, height} = gameWindow.size;
	const pixX = Math.floor(128*evt.clientX/width);
	const pixY = Math.floor(128*evt.clientY/height);
	return {
		x: pixX,
		y: pixY,
	}
}

addEventListener("dblclick", (evt) => {
	mouseEvents.push({type: "dblclick", button: evt.button, ...eventPixelCoords(evt)});
});

addEventListener("click", (evt) => {
	mouseEvents.push({type: "click", button: evt.button, ...eventPixelCoords(evt)});
});

addEventListener("mousedown", (evt) => {
	mouseButtonsDown[evt.button] = true;
	mouseEvents.push({type: "down", button: evt.button, ...eventPixelCoords(evt)});
});

addEventListener("mouseup", (evt) => {
	mouseButtonsDown[evt.button] = false;
	mouseEvents.push({type: "up", button: evt.button, ...eventPixelCoords(evt)});
});

addEventListener("mousemove", (evt) => {
	const coords = eventPixelCoords(evt);
	mouseEvents.push({type: "move", button: evt.button, ...eventPixelCoords(evt), prevX: mouseX, prevY: mouseY});
	mouseX = coords.x;
	mouseY = coords.y;
});

export const mousePos = () => {
	return {
		x: mouseX,
		y: mouseY,
	}
}

export const getMouseX = () => {
	return mouseX;
}

export const getMouseY = () => {
	return mouseY;
}

export const refreshMouse = () => {
	mouseEvents.length = 0;
}

export const mouseDown = (button: number = M.LEFT) => {
	return mouseEvents.some(ev => ev.button === button && ev.type === "down");
}

export const mouseClick = (button: number = M.LEFT) => {
	return mouseEvents.some(ev => ev.button === button && ev.type === "click");
}

export const mouseDoubleClick = (button: number = M.LEFT) => {
	return mouseEvents.some(ev => ev.button === button && ev.type === "dblclick");
}

export const mouseHeld = (button: number = M.LEFT) => {
	return mouseButtonsDown[button];
}