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

import com.tyr.Tyr;

import bwapi.Color;
import bwapi.Game;
import bwapi.Order;
import bwapi.Player;
import bwapi.Unit;


/**
 * This is an agent that helps control a worker.
 * @author Simon
 *
 */
public class WorkerAgent extends Agent
{
	/**
	 * The time until the worker is considered blocked in, or -1 if no timer is active.
	 * This is used when constructing a building.
	 * The worker is given a certain amount of time to go to the building location and start construction.
	 * If it does not start building within this time it is considered blocked in.
	 */
	public long blockedTimer = -1;
	
	/**
	 * When isBlocked is true, the worker is assumed to be blocked in.
	 * Only when it can prove that it is not blocked in, isBlocked will be set to false again.
	 * The worker can do this by mining from a mineral patch.
	 */
	public boolean isBlocked = false;
	
	public WorkerAgent(Unit unit)
	{
		super(unit);
	}
	
	/**
	 * This method is expected to be called every frame.
	 * @param game The game.
	 * @param self The player controlled by our bot.
	 * @param bot The instance of Tyr that is currently playing the game.
	 */
	public void onFrame(Game game, Player self, Tyr bot) 
	{
		// If the worker proves that it is not blocked in we set isBlocked to false.
		// The worker does this by mining from a mineral patch.
		if(isBlocked && unit.getOrder() == Order.MiningMinerals && unit.getTarget() != null 
				&& distanceSquared(unit.getTarget()) <= 50*50)
			isBlocked = false;
		
		// If the time runs out, the worker is considered blocked.
		if(game.getFrameCount() == blockedTimer)
		{
			blockedTimer = -1;
			isBlocked = true;
		}
		
		if(blockedTimer != -1)
			game.drawTextMap(unit.getX(), unit.getY()+10, (blockedTimer - game.getFrameCount()) + "");
		
		if(isBlocked)
		{
			drawCircle(Color.Red, 6);
			
			// When the timer runs out, it may turn out the worker was not blocked.
			// In this case we do not want it to place the building anyway, since this could lead to the building being consstructed twice.
			if(unit.getOrder() == Order.PlaceBuilding)
				unit.stop();
		}
	}
	
	

}
