package projectzombie.menu.gui;

import java.util.ArrayList;

import gl_engine.vec.Vec2d;

public class GUI implements GUIContainer
{
	private ArrayList<GUIComponent> components = new ArrayList<GUIComponent>();
	private Vec2d mousePos = new Vec2d(0, 0);
	
	public GUISelectable selected;
	
	private static boolean move_last = false;
	
	public void setSelected(GUISelectable selected) {
		if(this.selected != null) {
			this.selected.setSelected(false);
		}
		this.selected = selected;
		if(this.selected != null) {
			this.selected.setSelected(true);
		}
	}
	
	@Override
	public void render(Vec2d mousePos) {
		for(GUIComponent c : components) {
			c.render(mousePos);
		}
	}
	
	public void render() {
		this.render(mousePos);
	}

	@Override
	public void add(GUIComponent c) {
		components.add(c);
	}
	
	public void updateMousePos(Vec2d pos) {
		this.mousePos = pos;
	}
	
	public void onMove(boolean status, double angle)
	{
		if(this.selected == null) {
			return;
		}
		
		if(status) {
			if(!move_last) {
				move_last = true;
				
				this.selected.setSelected(false);
				GUISelectable selected = null;
				
				// Up / North
				if(angle > 315 || angle <= 45) {
					selected = this.selected.getNeighbour(GUISelectableDirection.UP);
				}
				
				// Right / East
				if(angle > 45 && angle <= 135) {
					selected = this.selected.getNeighbour(GUISelectableDirection.RIGHT);
				}
				
				// Down / South
				if(angle > 135 && angle <= 225) {
					selected = this.selected.getNeighbour(GUISelectableDirection.DOWN);
				}
				
				// Left / West
				if(angle > 225 && angle <= 315) {
					selected = this.selected.getNeighbour(GUISelectableDirection.LEFT);
				}
				
				if(selected != null) {
					this.selected = selected;
				}
				
				this.selected.setSelected(true);
			}
		}
		
		else if(move_last) {
			move_last = false;
		}
	}

	@Override
	public boolean checkMouseHover(Vec2d pos) {
		return false;
	}

	@Override
	public void onMouseClick(Vec2d pos) {
		for(GUIComponent c : components) {
			if(c.checkMouseHover(mousePos)) {
				c.onMouseClick(mousePos);
			}
		}
	}
	
	@Override
	public void onRightClick(Vec2d pos) {
		for(GUIComponent c : components) {
			if(c.checkMouseHover(mousePos)) {
				c.onRightClick(mousePos);
			}
		}
	}
	
	public void onMouseClick() {
		this.onMouseClick(mousePos);
	}
	
	public void onRightClick() {
		this.onRightClick(mousePos);
	}
	
	@Override
	public void onBack() {
		for(GUIComponent c : components) {
			c.onBack();
		}
	}
	
	@Override
	public void onActivate() {
		for(GUIComponent c : components) {
			c.onActivate();
		}
	}

	@Override
	public void update(Vec2d mousePos) {
		for(GUIComponent c : components) {
			c.update(mousePos);
		}
	}
	
}
