/*
* Tyr is an AI for StarCraft: Broodwar, 
* 
* Please visit https://github.com/SimonPrins/Tyr for further information.
* 
* Copyright 2015 Simon Prins
*
* This file is part of Tyr.
* Tyr is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
* Tyr is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with Tyr.  If not, see http://www.gnu.org/licenses/.
*/


package com.tyr.agents;

import java.util.List;

import com.tyr.EnemyManager;
import com.tyr.Tyr;

import bwapi.Game;
import bwapi.Player;
import bwapi.Unit;


/**
 * Orders an Agent to look for and kill enemy workers.
 * @author Simon
 *
 */
public class KillWorkers extends Command 
{
	/**
	 * The next worker we intend to kill.
	 */
	private Unit enemyWorker;
	
	/**
	 * Are we breaking off the command?
	 */
	public boolean breakOff = false;
	
	public KillWorkers(Agent agent)
	{
		super(agent);
	}

	@Override
	public void execute(Game game, Player self, Tyr bot)
	{
		// If we are under attack, we stop trying to kill workers.
		if (agent.unit.isUnderAttack())
			breakOff = true;
		
		// See if the enemy worker is still alive and if we are close enough to pursue him.
		if (enemyWorker != null)
		{
			if (enemyWorker.getHitPoints() <= 0 || enemyWorker.getRemoveTimer() != 0 || !enemyWorker.exists())
				enemyWorker = null;
			
			if (enemyWorker != null && agent.distanceSquared(enemyWorker) >= 320*320)
				enemyWorker = null;
		}
		
		// Select a next worker to kill.
		if (enemyWorker == null)
		{
			findWorker();
		
			if (enemyWorker != null)
				agent.unit.attack(enemyWorker);
		}
	}
	
	/**
	 * Finds an enemy worker to kill.
	 */
	private void findWorker() 
	{
		List<Unit> enemies = EnemyManager.getEnemyUnits();
		
		double bestDistance = Integer.MAX_VALUE;
		for(Unit enemy : enemies)
		{
			// We are only interested in workers.
			if (!(enemy.getType().isWorker()))
				continue;
			
			// find the distance to this new worker.
			double newDist = agent.distanceSquared(enemy);
			
			// Select the closest worker.
			if (enemyWorker == null || newDist < bestDistance)
			{
				enemyWorker = enemy;
				bestDistance = newDist;
			}
		}
	}

	@Override
	public boolean replace(Command command) 
	{
		return true;
	}
	
	public boolean getBreakOff()
	{
		return this.breakOff;
	}
}
