package pl.shockah.ts.menu;

import org.lwjgl.input.Keyboard;
import pl.shockah.Math2;
import pl.shockah.glib.geom.Rectangle;
import pl.shockah.glib.geom.vector.Vector2i;
import pl.shockah.glib.gl.Graphics;
import pl.shockah.glib.gl.color.Color;
import pl.shockah.glib.gl.font.ETextAlign;
import pl.shockah.glib.gl.font.Font;
import pl.shockah.glib.gl.font.TextHelper;
import pl.shockah.glib.gl.tex.Atlas;
import pl.shockah.glib.input.KInput;
import pl.shockah.glib.input.MInput;
import pl.shockah.glib.state.State;
import pl.shockah.ts.Assets;

public class MenuElButton extends MenuElement {
	public static final Atlas atlas = Assets.aFrameText;
	
	protected String text = "";
	protected Runnable action = null;
	protected float selectedAlpha = 0f;
	
	public MenuElButton setText(String text) {
		this.text = text;
		return this;
	}
	public MenuElButton setAction(Runnable action) {
		this.action = action;
		return this;
	}
	
	protected void create(MenuSet menu, boolean selected) {
		selectedAlpha = selected ? 1f : 0f;
	}
	
	protected boolean update(MenuSet menu, Rectangle rect, Font font, boolean selected) {
		selectedAlpha = Math2.limit(selectedAlpha+.1f*(selected ? 1 : -1),0,1);
		
		if (selected && KInput.isPressed(Keyboard.KEY_RETURN) && action != null) action.run();
		if (MInput.inRectangle(new Rectangle(0,rect.pos.y,State.get().getDisplaySize().x,rect.size.y))) {
			if (selected && MInput.isPressed(MInput.LEFT) && action != null) action.run();
			return !MInput.getDeltaPos().equals(new Vector2i());
		}
		return false;
	}
	protected void render(MenuSet menu, Graphics g, Rectangle rect, Font font, boolean selected) {
		g.setColor(Color.Black.alpha(.5f));
		g.draw(new Rectangle(0,rect.pos.y,State.get().getDisplaySize().x,rect.size.y));
		g.setColor(Color.Black.alpha(.5f*selectedAlpha));
		g.draw(new Rectangle(0,rect.pos.y,State.get().getDisplaySize().x,rect.size.y));
		
		g.setColor(Color.Black);
		for (int yy = -1; yy <= 1; yy += 2) for (int xx = -1; xx <= 1; xx += 2) TextHelper.draw(g,font,rect.pos.Add(xx,yy).add(rect.size.Div(2)),text,ETextAlign.MiddleCenter);
		g.setColor(Color.White);
		TextHelper.draw(g,font,rect.pos.Add(rect.size.Div(2)),text,ETextAlign.MiddleCenter);
	}
}