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

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


/**
 * A task that determines whether our main base needs defending and if so will try to defend it.
 */
public class DefendBaseTask extends Task
{
	/**
	 * The closest invading enemy unit.
	 */
	private Unit invader;
	
	/**
	 * What is the position we want to defend?
	 */
	private Position defensePos;
	
	/**
	 * What is the range at which we will consider an enemy an invader?
	 */
	private int range;
	
	/**
	 * Is this task still active?
	 */
	public boolean active = true;
	
	/**
	 * A task that determines whether our main base needs defending and if so will try to defend it.
	 */
	public DefendBaseTask(Position defensePos, int range)
	{
		this.defensePos = defensePos;
		this.range = range;
	}
	
	@Override
	public boolean isRequired(Game game, Player self, Tyr bot) 
	{
		return true;
	}

	@Override
	public void solve(Game game, Player self, Tyr bot)
	{
		determineInvader();
		
		
		
		// We set the position where we want the units to defend.
		if (invader != null)
			((SendTroopsSolution)solution).setTarget(invader.getPosition());
		else
			((SendTroopsSolution)solution).setTarget(defensePos);
		
		for (int i = bot.homeGroup.units.size()-1; i > ((SendTroopsSolution)solution).getCount(); i--)
		{
			((SendTroopsSolution)solution).add(bot.homeGroup.units.get(i));
			bot.homeGroup.units.remove(i);
		}
		
		// We call the super class, which will send the units out to defend.
		super.solve(game, self, bot);
	}

	private void determineInvader()
	{
		invader = null;
		double bestDist = range;
		for (Unit enemy : EnemyManager.getEnemyUnits())
		{
			if (Tyr.self.getRace() == Race.Protoss 
					&& !enemy.isDetected() 
					&& (enemy.getType() == UnitType.Protoss_Dark_Templar || enemy.isBurrowed()))
				continue;
			double newDist = enemy.getDistance(defensePos); 
			if (newDist >= bestDist)
				continue;
			
			invader = enemy;
		}
	}

	@Override
	public void findSolution(Game game, Player self, Tyr bot)
	{
		solution = new SendTroopsSolution(this, defensePos);
	}
}
