package ;
import flixel.text.pxText.PxTextAlign;
import flixel.text.FlxBitmapTextField;
import flixel.addons.ui.FlxUI9SliceSprite;
import openfl.geom.Rectangle;
import flixel.FlxSprite;
import flixel.group.FlxSpriteGroup;

class TextButton extends FlxSpriteGroup
{
	var backIdle:FlxSprite;
	var backPress:FlxSprite;
	var textField:FlxBitmapTextField;
	var clickChecker:ClickChecker;
	var onClick:Void->Void;

	public function new(rect:Rectangle, text:String, onClick_:Void->Void)
	{
		super();

		onClick = onClick_;

		backIdle = new FlxUI9SliceSprite(0, 0, "assets/images/Button-Idle.png", rect, [ 2, 2, 8, 8 ]);
		add(backIdle);

		backPress = new FlxUI9SliceSprite(0, 0, "assets/images/Button-Press.png", rect, [ 2, 2, 8, 8 ]);
		add(backPress);

		textField = new FlxBitmapTextField(Global.formFont);
		textField.textColor = 0xffffff;
		textField.fixedWidth = true;
		textField.alignment = PxTextAlign.CENTER;
		textField.width = Std.int(rect.width) - 8;
		textField.x = 4;
		textField.wordWrap = true;
		textField.multiLine = true;
		textField.text = text;
		textField.update();
		textField.y = Math.floor(rect.height / 2 - textField.height / 2) - 2;
		add(textField);

		x = rect.x;
		y = rect.y;

		clickChecker = new ClickChecker(this);
	}

	public override function update()
	{
		super.update();

		var clickResult = clickChecker.update();
		var hover = (clickResult & ClickChecker.HOVER) != 0;
		var click = (clickResult & ClickChecker.CLICK) != 0;

		backPress.visible = hover;
		backIdle.visible = !hover;
		textField.textColor = hover ? 0x000000 : 0xffffff;

		if (click && onClick != null) onClick();
	}
}
