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

import com.tyr.Tyr;
import com.tyr.agents.Agent;

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


/**
 * A task that defends our bases using air units.
 */
public class LocalDefenseTask extends Task
{
	public static boolean disabled = false;
	private int defendersNeeded;
	private Region defendedRegion;
	
	public LocalDefenseTask() { super();}
	
	public LocalDefenseTask(Region defendedRegion, int defendersNeeded)
	{
		super();
		this.defendedRegion = defendedRegion;
		this.defendersNeeded = defendersNeeded;
	}
	
	@Override
	public boolean isRequired(Game game, Player self, Tyr bot) 
	{
		return true;
	}
	
	@Override
	public void solve(Game game, Player self, Tyr bot)
	{
		for(int i = bot.homeGroup.units.size() - 1; i >= 0 && ((LocalDefenseSolution)solution).size() < defendersNeeded && !disabled; i--)
		{
			Agent agent = bot.homeGroup.units.get(i);

			if (agent.unit.getType() == UnitType.Protoss_Dragoon || agent.unit.getType() == UnitType.Terran_Goliath)
			{
				((LocalDefenseSolution)solution).add(agent);
				bot.homeGroup.units.remove(i);
			}
		}
		
		// We call the super class, which will send the units out to attack.
		super.solve(game, self, bot);
	}

	@Override
	public void findSolution(Game game, Player self, Tyr bot)
	{
		solution = new LocalDefenseSolution(this, defendedRegion);
	}
	
	/**
	 * The number of units which will defend the base.
	 * @param defendersNeeded The number of units which will defend the base.
	 */
	public void setDefendersNeeded(int defendersNeeded)
	{
		this.defendersNeeded = defendersNeeded;
	}
	
	/**
	 * The number of units which will defend the base.
	 * @return The number of units which will defend the base.
	 */
	public int getDefendersNeeded()
	{
		return defendersNeeded;
	}
	
	public void setDefendedPosition(Position defendedPosition)
	{
		((LocalDefenseSolution)solution).setDefendedPosition(defendedPosition);
	}
}
