/*
* 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 com.tyr.EnemyManager;
import com.tyr.EnemyPosition;
import com.tyr.Tyr;

import bwapi.Color;
import bwapi.Game;
import bwapi.Player;
import bwapi.TechType;
import bwapi.Unit;


public class FocusTarget extends Command
{
	private EnemyPosition target;
	
	public FocusTarget(Agent agent, EnemyPosition target)
	{
		super(agent);
		this.target = target;
	}
	
	@Override
	public void execute(Game game, Player self, Tyr bot) 
	{
		agent.drawCircle(Color.Red);
		
		Unit enemy = null;
		for(Unit unit : EnemyManager.getEnemyUnits())
		{
			if (unit.getType() != target.type)
				continue;

			if (Math.abs(unit.getX() - target.pos.getX()) > 10)
				continue;
			
			if (Math.abs(unit.getY() - target.pos.getY()) > 10)
				continue;
			
			enemy = unit;
		}
		
		if (enemy != null && agent.unit.isInWeaponRange(enemy))
		{
			if (agent.unit.getHitPoints() > agent.unit.getType().maxHitPoints() - 10 && !agent.unit.isStimmed()
					&& self.hasResearched(TechType.Stim_Packs))
			{
				agent.unit.useTech(TechType.Stim_Packs);
				return;
			}
			Unit agentTarget = agent.unit.getTarget();
			if(agentTarget == null || agentTarget.getID() != enemy.getID())
			{
				agent.unit.attack(enemy);
			}
			return;
		}
		
		if (agent.unit.getGroundWeaponCooldown() > 1 && agent.unit.getAirWeaponCooldown() > 1)
		{
			agent.unit.move(target.pos);
		}
		else if (agent.unit.isHoldingPosition() || agent.unit.isIdle() || agent.unit.getGroundWeaponCooldown() == 1 || agent.unit.getAirWeaponCooldown() == 1)
		{
			Tyr.drawCircle(agent.unit.getPosition(), Color.Green, 6);
			agent.attack(target.pos);
		}
	}
	
	@Override
	public boolean replace(Command command) 
	{
		if (!command.getClass().equals(FocusTarget.class))
			return true;
		
		FocusTarget atkCom = ((FocusTarget)command);
		if (atkCom.target.type != target.type)
			return true;
		if (atkCom.target.pos.getX() != target.pos.getX())
			return true;
		if (atkCom.target.pos.getY() != target.pos.getY())
			return true;
		
		return false;
	}
	
}
