package pl.mmorpg.prototype.client.states;

import java.util.Stack;
import java.util.function.Consumer;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import pl.mmorpg.prototype.client.exceptions.NoSuchStateTypeException;

public class StateManager
{
	private Stack<State> states = new Stack<State>();
	private Consumer<State> disposeState;

	public StateManager(Consumer<State> disposeState)
	{
		this.disposeState = disposeState;
	}

	public State usedState()
	{
		return states.peek();
	}

	public void update(float deltaTime)
	{
		usedState().update(deltaTime);
	}

	public void render(SpriteBatch batch)
	{
		usedState().render(batch);
	}

	public void set(State state)
	{
		State removedState = states.pop();
		disposeState.accept(removedState);
		states.push(state);
	}

	public void push(State state)
	{
		states.push(state);
	}

	public void pop()
	{
		states.pop();
		usedState().reactivate();
		if (states.empty())
			Gdx.app.exit();
	}

	public boolean empty()
	{
		return states.empty();
	}

	@SuppressWarnings(value = "unchecked")
	public <T> T find(Class<T> stateType)
	{
		for (State state : states)
			if (state.getClass().equals(stateType))
				return (T) state;
		throw new NoSuchStateTypeException();
	}

}

@@ -37,16 +37,43 @@
 tates;%0A%0A
+import java.util.Optional;%0A
 import j
@@ -205,16 +205,76 @@
 Batch;%0A%0A
+import pl.mmorpg.prototype.client.exceptions.GameException;%0A
 import p
@@ -406,21 +406,16 @@
 w Stack%3C
-State
 %3E();%0A%09pr
@@ -549,24 +549,37 @@
 %09%7D%0A%0A%09public 
+synchronized 
 State usedSt
@@ -619,24 +619,37 @@
 %09%7D%0A%0A%09public 
+synchronized 
 void update(
@@ -709,24 +709,37 @@
 %09%7D%0A%0A%09public 
+synchronized 
 void render(
@@ -797,24 +797,37 @@
 %09%7D%0A%0A%09public 
+synchronized 
 void set(Sta
@@ -943,24 +943,37 @@
 %09%7D%0A%0A%09public 
+synchronized 
 void push(St
@@ -1020,16 +1020,29 @@
 %09public 
+synchronized 
 void pop
@@ -1144,16 +1144,29 @@
 %09public 
+synchronized 
 boolean 
@@ -1257,18 +1257,182 @@
 lic 
-%3CT%3E T find
+synchronized %3CT%3E T find(Class%3CT%3E stateType)%0A%09%7B%0A%09%09return findOptionally(stateType)%0A%09%09%09%09.orElseThrow(NoSuchStateTypeException::new);%0A%09%7D%0A%0A%09private %3CT%3E Optional%3CT%3E findOptionally
 (Cla
@@ -1534,16 +1534,28 @@
 %09return 
+Optional.of(
 (T) stat
@@ -1559,52 +1559,39 @@
 tate
+)
 ;%0A%09%09
-throw new NoSuchStateTypeException
+return Optional.empty
 ();%0A%09%7D%0A
-%0A
 %7D%0A

Fix bug when changing states