package ei.game.player;

import java.util.ArrayList;

import ei.game.network.entities.NetworkPlayer;
import ei.game.scene.GameEntity;
import ei.game.scene.buildings.Building;
import ei.game.scene.buildings.CommandCenter;
import ei.game.scene.units.APU;
import ei.game.scene.units.Bomber;
import ei.game.scene.units.Tank;
/**
 * The AiPlayer class.
 * @author Jesper Lundin
 *
 */

public class AiPlayer extends NetworkPlayer{
	private CommandCenter cc;
	private int timer;
	private ArrayList<GameEntity> attackingUnits;
	
	/**
	 * Constructor for the AiPlayer class. Creates a temporary
	 *
	 */
	public AiPlayer(){
		super();
		cc = new CommandCenter(30,25,this);
		addUnit(cc);
		attackingUnits = new ArrayList<GameEntity>();
	}
	
	@Override
	public Building getCC() {
		return cc;
	}
	/**
	 * Handles the actions for the computer controlled player.
	 */
	public void update() {
		super.update();
		if(getKredits() >= 800 && cc.getBuildQueueSize()==0) {
			int unitToBuild = (int)(Math.random()*2);
			if(unitToBuild==0) {
				cc.buildUnit(new APU(this));
			}
			else if(unitToBuild==1) {
				cc.buildUnit(new Tank(this));
			}
			else if(unitToBuild==2) {
				cc.buildUnit(new Bomber(this));
			}
		}
		if((unitCount()>=10 || attackingUnits.size()>=2) && timer%100==0) {
			for(int i=0; i < unitCount(); i++) {
				if(!attackingUnits.contains(getUnit(i))) {
					attackingUnits.add(getUnit(i));
					if(!getUnit(i).isAttacking() && !getUnit(i).isMoving()){
						attackingUnits.get(i).move(false, attackingUnits.get(i).getPos().getX()-2, attackingUnits.get(i).getPos().getY()-2);
					}
				}
			}
		}
		else{
			attackingUnits.clear();
		}
		timer++;
		removeDead();
		
	}
	/**
	 * Removes the dead units from the temporary army.
	 *
	 */
	public void removeDead(){
		for(int i=0; i<attackingUnits.size() ;i++){
			if(attackingUnits.get(i).getLife() <= 0){
				attackingUnits.remove(i);
			}
		}
	}
	
	/**
	 * Defeated if the command center is dead.
	 */
	public boolean defeated() {
		if(cc.getLife() <= 0){
			return true;
		}

		return false;
	}

	/**
	 * Game over man! Game over!
	 */
	public void endGame(int s) {
		
	}
}
