package ei.engine.state;

import java.util.ArrayList;

public class GameStateManager {
	private static GameStateManager instance;
	private ArrayList<GameState> gameStates;
	
	private GameStateManager(){
		gameStates = new ArrayList<GameState>();
	}
	
	/**
	 * Add A GameState to the GameStateManager
	 * @param g The GameState to add
	 * @return true if successful else false
	 */
	public boolean addState(GameState g){
		if(!gameStates.contains(g)){
			gameStates.add(g);
			return true;
		}
		return false;
	}
	
	/**
	 * Remove a GameState from the GameStateManager
	 * @param g The state to remove
	 * @return true if successful else false
	 */
	public boolean removeState(GameState g){
		if(gameStates.contains(g)){
			gameStates.remove(g);
			return true;
		}
		return false;
	}
	
	/**
	 * Removes a GameState by its name
	 * @param name the name of the GameState to remove
	 * @return true if successful else false
	 */
	public boolean removeStateByName(String name){
		int i = getId(name);
		if(i >= 0){
			gameStates.remove(i);
			return true;
		}
		return false;
	}
	
	/**
	 * Returns the GameState in GameStateManager whit the given name
	 * @param name the name of the GameState
	 * @return the GameState by the name else null
	 */
	public GameState getState(String name){
		int i = getId(name);
		if(i >= 0){
			return gameStates.get(i);
		}
		return null;
	}
	
	/**
	 * Activates a GameState by the name
	 * @param name the name of the GameState
	 * @return true if successful else false
	 */
	public boolean setActive(String name){
		GameState g = getState(name);
		if(g != null){
			g.setEnabled(true);
			return true;
		}
		return false;
	}
	
	/**
	 * Deactivates a GameState by the name
	 * @param name the name of the GameState
	 * @return true if successful else false
	 */
	public boolean setDeActive(String name){
		GameState g = getState(name);
		if(g != null){
			g.setEnabled(false);
			return true;
		}
		return false;
	}
	
	/**
	 * Searches for the given name of a GameState
	 * @param name The name of the GameState
	 * @return The index of the GameState
	 */
	private int getId(String name){
		for(int i=0; i<gameStates.size() ;i++){
			if(gameStates.get(i).getName().equals(name)){
				return i;				
			}
		}
		return -1;
	}
	
	/**
	 * updates all the active GameStates
	 */
	public void update(){
		for(int i=0; i<gameStates.size() ;i++){
			if(gameStates.get(i).isEnabled()){
				gameStates.get(i).stateUpdate();
			}
		}
	}
	
	/**
	 * renders all the active GameStates
	 */
	public void render(){
		for(int i=0; i<gameStates.size() ;i++){
			if(gameStates.get(i).isEnabled()){
				gameStates.get(i).stateRender();
			}
		}
	}
	
	public static GameStateManager getInstance(){
		if(instance == null){
			instance = new GameStateManager();
		}
		return instance;
	}
}
