/*
* 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.unitgroups;

import com.tyr.BWTAProxy;
import com.tyr.Tyr;
import com.tyr.agents.Agent;
import com.tyr.agents.Attack;
import com.tyr.buildingplacement.SpaceManager;

import bwapi.Game;
import bwapi.Player;
import bwapi.Position;
import bwapi.UnitType;


/**
 * A unit group for sending units to attack a certain location.
 * @author Simon
 *
 */
public class AttackNaturalGroup extends IAttackGroup
{
	public static int clearDistance = 400;
	public static int smallRetreatDistance = 500;
	public static int largeRetreatDistance = 650;
	boolean pullingBack = false;
	private Position enemyNatural = null;
	
	/**
	 * A unit group for sending units to attack a certain location.
	 * @param target The target where we want the units to attack.
	 */
	public AttackNaturalGroup(Position target) 
	{
		super(target);
	}

	@Override
	public void onFrame(Game game, Player self, Tyr bot)
	{
		if (BWTAProxy.initialized && Tyr.game.getFrameCount() > 100 && Tyr.bot.suspectedEnemy.size() == 1)
			enemyNatural = SpaceManager.getEnemyNatural().getPosition();
		
		final boolean pulledBackPrev = pullingBack;
		boolean retreat = true;
		if (units.size() >= 30 || self.supplyUsed() >= 360)
			retreat = false;
		
		// Order all units to attack the target.
		for (Agent agent : units)
		{
			if (agent.unit.getType() == UnitType.Protoss_Reaver)
			{
				if (!agent.unit.isTraining() && agent.unit.getScarabCount() < 5)
					agent.unit.train(UnitType.Protoss_Scarab);
			}

			if (retreat && enemyNatural != null && agent.distanceSquared(enemyNatural) <= Math.pow(pulledBackPrev?largeRetreatDistance:smallRetreatDistance, 2))
			{
				pullingBack = true;
				agent.unit.move(Tyr.tileToPosition(self.getStartLocation()));
				continue;
			}
				
			agent.order(new Attack(agent, target));
		}
	}
}
