package ei.game.player;

import java.util.ArrayList;

import ei.engine.scene.Node;
import ei.game.gamestate.EndGameState;

public class PlayerHandler {
	// The instance of this class
	private static PlayerHandler instance;
	// The player list
	private ArrayList<Player> players;
	private Node playerNode;
	// economy stuff
	private static final int fundsDelay = 60*30;
	private static final int funds = 1000;
	private int fundsTimmer;
	private Player gaia;
	
	/**
	 * Creates a PlayerHandler
	 *
	 */
	public PlayerHandler(){
		players = new ArrayList<Player>();
		playerNode = new Node("PlayerNode");
		fundsTimmer = 0;
	}
	
	/**
	 * Returns a node with all the players units
	 * 
	 * @return A node with all the players units
	 */
	public Node getNode(){
		return playerNode;
	}
	
	/**
	 * Add a player to the handler
	 * 
	 * @param p The player to add to the handler
	 * @return true if added else false
	 */
	public boolean addPlayer(Player p){
		if(!players.contains(p)){
			players.add(p);
			playerNode.add(p.getNode());
			return true;
		}
		return false;
	}
	
	/**
	 * Removes a player from the handler
	 * @param p The player to remove
	 * @return true if succesful else false
	 */
	public boolean removePlayer(Player p){
		if(players.contains(p)){
			players.remove(p);
			playerNode.remove(p.getNode());
			return true;
		}
		return false;
	}
	
	public void update(){
		//****** ECONOMY **************
		// sends the funds to the players
		fundsTimmer++;
		if(fundsTimmer >= fundsDelay){
			for(int i=0; i<players.size() ;i++){
				int maintenance = 0;
				for(int j=0; j<players.get(i).unitCount() ;j++){
					maintenance += players.get(i).getUnit(j).getMaintenanceCost();
				}
				int kredit = funds - maintenance;
				if(kredit > 0){
					players.get(i).addKredits(kredit);
				}
			}
			fundsTimmer = 0;
		}
		//*******************************
		// updates the players
		for(int i=0; i<players.size() ;i++){
			if(players.get(i).defeated()){
				players.get(i).kilAll();
				players.get(i).endGame(EndGameState.DEFEAT);
				players.remove(i);
				if(players.size() == 1){
					players.get(0).endGame(EndGameState.VICTORY);
				}
			}
			else{
				players.get(i).update();
			}
		}
		if(gaia != null)gaia.update();
	}
	
	/**
	 * Returns the instance of this class
	 * 
	 * @return The instance
	 */
	public static PlayerHandler getInstance(){
		if(instance == null){
			instance = new PlayerHandler();
		}
		return instance;
	}
	
	public void clear(){
		players.clear();
		playerNode.clear();
		fundsTimmer = 0;
	}
		
	public void setGaiaPlayer(Player p){
		if(gaia != null && playerNode.contains(gaia.getNode())){
			playerNode.remove(gaia.getNode());
		}
		gaia = p;
		playerNode.add(gaia.getNode());
	}
}
