package org.mote.wiimote.whiteboard.mouse;

import java.awt.AWTException;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.InputEvent;

import org.mote.wiimote.whiteboard.preferences.WWPreferences;

public enum Mouse {
	LEFT_BUTTON(InputEvent.BUTTON1_MASK), RIGHT_BUTTON(InputEvent.BUTTON3_MASK);
	
	private static final WWPreferences prefs = WWPreferences.getPreferences();
	private static Point position = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
	private static Robot r;
	private static Rectangle bounds; 
	
	private final int id;
	private long lastReleased = -1, lastPressed = -1;
	private boolean pressed;
	
	static {
		final GraphicsDevice screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
		try {
			r = new Robot(screen);
			setScreen(screen);
		} catch (AWTException e) {
			e.printStackTrace();
		} 
	}
	
	private Mouse(int id) {
		this.id = id;
	}
	
	public static void setScreen(GraphicsDevice screen) {

	}
	
	public static void sleep(int ms) {
		r.delay(ms);
	}
	
	public static void move(Point p) {
		if (!(prefs.assistDoubleClicks() && position.distance(p) < WWPreferences.PIXEL_MOVE_TOLERANCE && (
			(Mouse.LEFT_BUTTON.isPressed() && System.currentTimeMillis() - Mouse.LEFT_BUTTON.getLastPressed() < WWPreferences.SHORT_DELAY) ||
			(!Mouse.LEFT_BUTTON.isPressed() && System.currentTimeMillis() - Mouse.LEFT_BUTTON.getLastReleased() < WWPreferences.SHORT_DELAY)
		))) {
			r.mouseMove(Math.min(Math.max(bounds.x, p.x), bounds.x+bounds.width-1), Math.min(Math.max(bounds.y, p.y), bounds.y+bounds.height-1));
			position = p;
		}
	}
	
	public static Point getPosition() {
		return position;
	}
	
	public boolean isPressed() {
		return pressed;
	}
	
	public void setPressed(boolean pressRequest) {
		if (pressRequest && !pressed) {
			r.mousePress(id);
			lastPressed = System.currentTimeMillis();
		} else if (!pressRequest && pressed) {
			r.mouseRelease(id);
			lastReleased = System.currentTimeMillis();
		}
		this.pressed = pressRequest;
	}
	
	public long getLastPressed() {
		return lastPressed;
	}
	
	public long getLastReleased() {
		return lastReleased;
	}
}
