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

import bwapi.Game;
import bwapi.Player;
import bwapi.Unit;


/**
 * A task to clear blocking mineral patches.
 */
public class ClearMineralTask extends Task
{
	@Override
	public boolean isRequired(Game game, Player self, Tyr bot) 
	{	
		if (solution != null)
			return true;
		
		if (game.getFrameCount() < 10)
			return false;
		
		return solution != null || getBlockingMineral() != null;
	}
	
	@Override
	public void solve(Game game, Player self, Tyr bot)
	{
		ClearMineralSolution clearSolution = (ClearMineralSolution)solution;
		
		// If the mineral patch is removed, we no longer need the solution.
		if (clearSolution.finished)
		{
			Agent worker = clearSolution.pop();
			if (worker != null)
				bot.hobos.add(worker);
			solution = null;
			return;
		}
		
		if (clearSolution.workerNeeded())
			clearSolution.setWorker(bot.workForce.pop(clearSolution.getPosition()));
		
		// We call the super class.
		super.solve(game, self, bot);
	}

	@Override
	public void findSolution(Game game, Player self, Tyr bot)
	{
		solution = new ClearMineralSolution(this, getBlockingMineral().getPosition());
	}
	
	/**
	 * Finds a blocking mineral patch and returns it.
	 * @return The blocking mineral patch, or null if no blocking mineral patch is found.
	 */
	private Unit getBlockingMineral()
	{
		Unit blockingMineral = null;
		
		for(Unit mineral : Tyr.game.neutral().getUnits())
		{
			if (!mineral.getType().isMineralField())
				continue;
			
			if(mineral.getResources() > 0)
				continue;
			
			if (mineral.getDistance(Tyr.tileToPosition(Tyr.self.getStartLocation())) >= Settings.getLargeInvasionDist())
				continue;
			
			blockingMineral = mineral;
			break;
		}
		
		return blockingMineral;
	}
}
