import openfl.events.MouseEvent;
import openfl.text.TextField;
import openfl.display.Sprite;

class Button extends Sprite {
	static final BG_COLOR:Int = 0x0000ff;
	static final BG_ACTIVE:Int = 0xff0000;

	var bgWidth:Float;
	var bgHeight:Float;

	var toggle:Bool;

	public var action:Void->Void;

	public var selected(default, set):Bool = false;

	function set_selected(value:Bool):Bool {
		selected = value;
		drawBg();
		return selected;
	}

	public function new(title:String, ?toggle:Bool = false, ?action:Void->Void = null) {
		super();

		this.action = action;
		this.toggle = toggle;

		var caption = new TextField();
		caption.autoSize = LEFT;
		caption.selectable = false;
		caption.text = title;
		caption.textColor = 0xffffff;

		bgWidth = caption.width + 20;
		bgHeight = caption.height + 20;

		drawBg();

		caption.x = (width - caption.width) / 2;
		caption.y = (height - caption.height) / 2;
		addChild(caption);

		buttonMode = true;

		addEventListener(MouseEvent.CLICK, onClick);
	}

	function onClick(event:MouseEvent) {
		if (toggle) {
			selected = !selected;
		}

		if (action != null)
			action();
	}

	function drawBg() {
		graphics.beginFill(selected ? BG_ACTIVE : BG_COLOR);
		graphics.drawRoundRect(0, 0, bgWidth, bgHeight, 10);
		graphics.endFill();
	}
}
