package ;
import openfl.geom.Rectangle;
import flixel.FlxObject;
import flixel.FlxG;
import flixel.util.FlxPoint;

class ClickChecker
{
	var pressing:Bool;
	var host:FlxObject;

	public var enabled:Bool = true;
	public var hitRect:Rectangle = null;
	public var buttonUpSound:String = "Button-Up.mp3";

	public static var HOVER = 1<<0;
	public static var CLICK = 1<<1;

	public function new(host_:FlxObject)
	{
		host = host_;
	}

	public function update():Int
	{
		var result = 0;

		if (host.visible && enabled)
		{
			var pos = FlxPoint.weak(FlxG.mouse.screenX, FlxG.mouse.screenY);
			var mouseOver = host.overlapsPoint(pos);

			if (mouseOver && hitRect != null)
			{
				mouseOver = mouseOver && hitRect.contains(pos.x-host.x, pos.y-host.y);
			}

			if (pressing && Capture.take(host))
			{
				if (!FlxG.mouse.pressed)
				{
					// click
					pressing = false;
					if (mouseOver) result |= CLICK;
					Capture.release(host);
					//Util.playSound("Click-Up.mp3");

					if (buttonUpSound != null) Main.playSound(buttonUpSound);
				}
				else
				{
					if (mouseOver) result |= HOVER;
				}
			}
			else if (Capture.justPressed() && mouseOver)
			{
				pressing = true;
				result |= HOVER;
				Capture.take(host);
				//Util.playSound("Click-Down.mp3");
				Main.playSound("Button-Down.mp3");
			}
		}
		else
		{
			// hidden or disabled
			Capture.release(host);
		}

		return result;
	}
}
