/*
* 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 com.tyr.agents.Agent;
import com.tyr.agents.None;
import com.tyr.agents.VultureAgent;

import bwapi.Game;
import bwapi.Player;
import bwapi.TechType;


/**
 * A task that lays down a minefield of spider mines.
 */
public class LayMinesTask extends Task
{
	@Override
	public boolean isRequired(Game game, Player self, Tyr bot) 
	{	
		if (solution != null)
			return true;
		
		return solution != null || self.hasResearched(TechType.Spider_Mines);
	}
	
	@Override
	public void solve(Game game, Player self, Tyr bot)
	{
		MineGridSolution mineSolution = (MineGridSolution)solution;
		// Do not lay mines when the opponent is attacking.
		if (EnemyManager.getManager().getInvaderCount() > 0)
		{
			// If the solution has a previous vulture, we need to return it to the homegroup.
			Agent previous = mineSolution.pop();
			if (previous != null)
			{
				previous.order(new None(previous));
				if (previous != null)
					bot.homeGroup.add(previous);
			}

			// We call the super class.
			super.solve(game, self, bot);
			return;
		}
		if (mineSolution.vultureNeeded())
		{
			// If the solution has a previous vulture, we need to return it to the homegroup.
			Agent previous = mineSolution.pop();
			if (previous != null)
				bot.homeGroup.add(previous);
			
			// We try to find a new vulture to lay spider mines.
			for(int i=0; i< bot.homeGroup.units.size(); i++)
			{
				Agent agent = bot.homeGroup.units.get(i);
				if (agent instanceof VultureAgent
						&& agent.unit.getSpiderMineCount() > 0
						&& !((VultureAgent)agent).isBlocked)
				{
					bot.homeGroup.remove(i);
					mineSolution.setVulture((VultureAgent)agent);
					break;
				}
			}
		}
		
		// We call the super class.
		super.solve(game, self, bot);
	}

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