package pl.shockah.ts.menu;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.lwjgl.input.Keyboard;
import pl.shockah.glib.geom.Rectangle;
import pl.shockah.glib.geom.vector.Vector2d;
import pl.shockah.glib.geom.vector.Vector2f;
import pl.shockah.glib.geom.vector.Vector2i;
import pl.shockah.glib.gl.Graphics;
import pl.shockah.glib.gl.font.Font;
import pl.shockah.glib.input.KInput;
import pl.shockah.glib.logic.standard.EntityRenderable;

public class MenuSet extends EntityRenderable {
	protected final List<MenuElement> elements = new LinkedList<>();
	protected Font font = null;
	protected Vector2d size = new Vector2d();
	protected double separator = 0;
	protected int selected = 0;
	
	public MenuSet setSize(Vector2d v) {return setSize(v.x,v.y);}
	public MenuSet setSize(Vector2f v) {return setSize(v.x,v.y);}
	public MenuSet setSize(Vector2i v) {return setSize(v.x,v.y);}
	public MenuSet setSize(double x, double y) {
		size.set(x,y);
		return this;
	}
	
	public MenuSet setSeparator(double separator) {
		this.separator = separator;
		return this;
	}
	
	public MenuSet setFont(Font font) {
		this.font = font;
		return this;
	}
	
	public MenuSet addElements(MenuElement... elements) {
		this.elements.addAll(Arrays.asList(elements));
		return this;
	}
	
	protected void onCreate() {
		int i = 0;
		
		for (MenuElement mel : elements) mel.create(this,selected == i++);
	}
	
	protected void onUpdate() {
		double yy = 0;
		int i = 0, newSelected = -1;
		
		boolean locked = elements.get(selected).lockedSelection();
		if (!locked) {
			if (KInput.isPressed(Keyboard.KEY_UP)) selected = Math.max(selected-1,0);
			if (KInput.isPressed(Keyboard.KEY_DOWN)) selected = Math.min(selected+1,elements.size()-1);
		}
		
		Vector2d v = new Vector2d(size.x/2,size.y/2);
		for (MenuElement mel : elements) {
			if (mel.update(this,new Rectangle(pos.Add(0,yy).sub(v),size),font,selected == i++)) newSelected = i-1;
			yy += size.y+separator;
		}
		if (!locked && newSelected != -1) selected = newSelected;
	}
	
	protected void onRender(Graphics g) {
		double yy = 0; int i = 0; Vector2d v = new Vector2d(size.x/2,size.y/2);
		for (MenuElement mel : elements) {
			mel.render(this,g,new Rectangle(pos.Add(0,yy).sub(v),size),font,selected == i++);
			yy += size.y+separator;
		}
		
		yy = 0; i = 0; v.set(size.x/2,size.y/2);
		for (MenuElement mel : elements) {
			mel.render2(this,g,new Rectangle(pos.Add(0,yy).sub(v),size),font,selected == i++);
			yy += size.y+separator;
		}
	}
}