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

import com.tyr.DebugMessages;
import com.tyr.Settings;
import com.tyr.StopWatch;
import com.tyr.Tyr;
import com.tyr.UnitTracker;
import com.tyr.agents.Agent;
import com.tyr.tasks.DoomDropTask;
import com.tyr.tasks.ExploreScienceSolution;
import com.tyr.tasks.ExploreScienceTask;
import com.tyr.unitgroups.MineralWorkers;
import com.tyr.unitgroups.HomeGroup;

import bwapi.Game;
import bwapi.Player;
import bwapi.TechType;
import bwapi.UnitType;
import bwapi.UpgradeType;


/**
 * A defensive mech build designed to stop Ironbot.
 * @author Simon
 *
 */
public class AntiIron extends CompositeBuildOrder
{
	int turretPos;
	
	@Override
	public void initialize(Game game, Player self, Tyr bot)
	{
		Settings.setRequiredSize(60);
		Settings.setMaximumSize(60);
		Settings.setWorkersPerGas(3);
		
		Settings.setLargeInvasionDist(720);
		Settings.setMaximumWorkers(30);
		
		HomeGroup.keepTanksSieged = true;
		
		this.add(new SupplyDepotPart());
		this.add(new WorkerScoutPart(1600));
		this.add(new ExpandPart(true));
		ExpandPart.maximumCcs = 1;
		bot.taskManager.potentialTasks.add(new DoomDropTask());
		bot.taskManager.potentialTasks.add(new ExploreScienceTask());
		
		super.initialize(game, self, bot);
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot)
	{
		DebugMessages.addMessage("Going defensive mech.");
		
		StopWatch watch = new StopWatch();
		long time;
		watch.start();
		
		super.onFrame(game, self, bot);
		
		if (UnitTracker.count(UnitType.Terran_Factory)  < 1 && (bot.getAvailableGas() >= 100 || bot.getAvailableMinerals() < 100))
			Settings.setWorkersPerGas(1);
		else if ( (UnitTracker.count(UnitType.Terran_Factory)  <= 2 || bot.getAvailableGas() >= 300 )  
				&& (bot.getAvailableGas() >= 100 || bot.getAvailableMinerals() < 150))
			Settings.setWorkersPerGas(2);
		else
			Settings.setWorkersPerGas(3);
		
		if (ExpandPart.maximumCcs == 1 && ExploreScienceSolution.done)
			ExpandPart.maximumCcs = 2;
		
		if (ExpandPart.maximumCcs == 2)
			DebugMessages.addMessage("Expanding.");
		
		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Mech super time: " + time);
		
		//if we've the resources to build a barracks ...
		if(bot.getAvailableMinerals() >= 100 
				&& UnitTracker.count(UnitType.Terran_Refinery) > 0
				&& (bot.getAvailableMinerals() >= 150 || UnitTracker.getCcCount() > 1)
				&& (UnitTracker.count(UnitType.Terran_Barracks) == 0)) 
		{
			bot.spaceManager.build(UnitType.Terran_Barracks);
		}
		
		if(UnitTracker.count(UnitType.Terran_Refinery) < UnitTracker.count(UnitType.Terran_Command_Center)
				&& (UnitTracker.count(UnitType.Terran_Refinery) == 0 || UnitTracker.count(UnitType.Terran_Factory) >= 1)
				&& bot.getAvailableMinerals() >= 100 
				&& UnitTracker.getGeyserCount() > 0)
		{
			bot.spaceManager.build(UnitType.Terran_Refinery);
		}
		
		if(bot.getAvailableMinerals() >= 200 && bot.getAvailableGas() >= 100
				&& UnitTracker.count(UnitType.Terran_Barracks) >= 1 
				&& UnitTracker.count(UnitType.Terran_Factory) < 3*UnitTracker.count(UnitType.Terran_Command_Center)
				&& (UnitTracker.count(UnitType.Terran_Factory) < 2 || UnitTracker.countTanks() > 0)
			)
		{
			bot.spaceManager.build(UnitType.Terran_Factory);
		}

		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Mech tier 1 time: " + time);
				time = watch.time();
		
		if (UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) + UnitTracker.count(UnitType.Terran_Siege_Tank_Tank_Mode) >= 4
				&& UnitTracker.count(UnitType.Terran_Armory) < 2
				&& bot.getAvailableGas() >= 50
				&& bot.getAvailableMinerals() >= 100)
		{
			bot.spaceManager.build(UnitType.Terran_Armory);
		}
		
		if (UnitTracker.count(UnitType.Terran_Armory) >= 2
				&& self.completedUnitCount(UnitType.Terran_Factory) >= 3
				&& UnitTracker.count(UnitType.Terran_Starport) == 0
				&& bot.getAvailableGas() >= 100
				&& bot.getAvailableMinerals() >= 150)
		{
			bot.spaceManager.build(UnitType.Terran_Starport);
		}
		
		if (UnitTracker.count(UnitType.Terran_Armory) >= 2
				&& UnitTracker.count(UnitType.Terran_Science_Facility) < 1
				&& self.completedUnitCount(UnitType.Terran_Starport) > 0
				&& bot.getAvailableGas() >= 150
				&& bot.getAvailableMinerals() >= 100)
		{
			bot.spaceManager.build(UnitType.Terran_Science_Facility);
		}
		
		if (UnitTracker.countTanks() >= 2
				&& bot.getAvailableMinerals() >= 125
				&& UnitTracker.count(UnitType.Terran_Engineering_Bay) == 0)
		{
			bot.spaceManager.build(UnitType.Terran_Engineering_Bay);
		}
		
		if(self.completedUnitCount(UnitType.Terran_Engineering_Bay) >= 1 && bot.getAvailableMinerals() >= 75)
		{
			boolean built = false;
			
			for (int i=0; i<bot.workForce.mineralWorkers.size(); i++)
			{
				MineralWorkers workers = bot.workForce.mineralWorkers.get((i + turretPos)%bot.workForce.mineralWorkers.size());
				if (bot.spaceManager.build(UnitType.Terran_Missile_Turret, null, workers.turretSite))
				{
					built = true;
					turretPos = (i + turretPos + 1)%bot.workForce.mineralWorkers.size();
					break;
				}
			}
			if (!built)
				DebugMessages.addMessage("No placement found for any turret.");
		}
		
		if (bot.getAvailableMinerals() >= 75
				&& self.completedUnitCount(UnitType.Terran_Engineering_Bay) > 0
				&& bot.defensiveStructures.get(0).getUnitCount(UnitType.Terran_Missile_Turret) == 0)
		{
			bot.spaceManager.buildDefensive(UnitType.Terran_Missile_Turret, bot.defensiveStructures.get(0));
		}
		
		
		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Mech tier 2 time: " + time);
	}

	@Override
	public boolean overrideStructureOrder(Game game, Player self, Tyr bot, Agent agent)
	{
		if(super.overrideStructureOrder(game, self, bot, agent))
			return true;
		
		if(agent.unit.getType() == UnitType.Terran_Barracks)
		{
			return true;
		}
		
		if(agent.unit.getType() == UnitType.Terran_Starport)
		{
			if (agent.unit.getAddon() == null 
					&& bot.getAvailableMinerals() >= 50 && bot.getAvailableGas() >= 50)
				agent.unit.buildAddon(UnitType.Terran_Control_Tower);
			else if (!agent.unit.isTraining() && UnitTracker.count(UnitType.Terran_Dropship) < 4
					&& bot.getAvailableMinerals() >= 100&& bot.getAvailableGas() >= 100
					&& agent.unit.getAddon() != null)
				agent.unit.train(UnitType.Terran_Dropship);
			else if (!agent.unit.isTraining() 
					&& UnitTracker.count(UnitType.Terran_Science_Vessel) == 0
					&& UnitTracker.count(UnitType.Terran_Dropship) >= 4
					&& bot.getAvailableMinerals() >= 100 && bot.getAvailableGas() >= 225
					&& agent.unit.getAddon() != null)
				agent.unit.train(UnitType.Terran_Science_Vessel);
			return true;
		}
		
		if (agent.unit.getType() == UnitType.Terran_Factory)
		{
			if (agent.unit.getAddon() != null)
			{
				if (UnitTracker.countTanks() >= 6 
						&& UnitTracker.count(UnitType.Terran_Dropship) >= 4
						&& UnitTracker.count(UnitType.Terran_Science_Vessel) == 0)
					return true;
				
				if (UnitTracker.count(UnitType.Terran_Factory) <= 1 
						&& UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) + UnitTracker.count(UnitType.Terran_Siege_Tank_Tank_Mode) >= 2)
					return false;
				return !self.isResearching(TechType.Tank_Siege_Mode) && !self.hasResearched(TechType.Tank_Siege_Mode);
			}

			boolean addonWanted = UnitTracker.usableAddOns(UnitType.Terran_Machine_Shop)*4 + 1 < self.completedUnitCount(UnitType.Terran_Factory)
					|| self.completedUnitCount(UnitType.Terran_Factory) <= 1;
			
			if(Tyr.self.completedUnitCount(UnitType.Terran_Armory) >= 1 
					&& !agent.unit.isTraining() 
					&& bot.getAvailableMinerals() >= 100 
					&& bot.getAvailableGas() >= 50
					&& UnitTracker.count(UnitType.Terran_Goliath) < 4)
				agent.unit.train(UnitType.Terran_Goliath);
			
			if (bot.getAvailableMinerals() >= 75 
					&& !agent.unit.isTraining() 
					&& UnitTracker.count(UnitType.Terran_Vulture) <= 2*(UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) + UnitTracker.count(UnitType.Terran_Siege_Tank_Tank_Mode)) - 1
					&& (UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) + UnitTracker.count(UnitType.Terran_Siege_Tank_Tank_Mode) >= 2
						|| bot.getAvailableMinerals() >= 300))
			{
				agent.unit.train(UnitType.Terran_Vulture);
				return true;
			}
			
			return !addonWanted;
		}
		else if(agent.unit.getType() == UnitType.Terran_Armory)
		{
			if(bot.getAvailableMinerals() >= UpgradeType.Terran_Vehicle_Weapons.mineralPrice()
					&& bot.getAvailableGas() >= UpgradeType.Terran_Vehicle_Weapons.gasPrice())
				agent.unit.upgrade(UpgradeType.Terran_Vehicle_Weapons);
			
			if(bot.getAvailableMinerals() >= UpgradeType.Terran_Vehicle_Plating.mineralPrice()
					&& bot.getAvailableGas() >= UpgradeType.Terran_Vehicle_Plating.gasPrice())
				agent.unit.upgrade(UpgradeType.Terran_Vehicle_Plating);
			
			return true;
		}
		else if (agent.unit.getType() == UnitType.Terran_Engineering_Bay)
		{
			return true;
		}
		else if (agent.unit.getType() == UnitType.Terran_Machine_Shop)
		{
			if (!self.hasResearched(TechType.Tank_Siege_Mode) && !self.isResearching(TechType.Tank_Siege_Mode))
				return false;

			if (self.completedUnitCount(UnitType.Terran_Armory) > 0
					&& !agent.unit.isResearching() && self.hasResearched(TechType.Tank_Siege_Mode)
					&& bot.getAvailableMinerals() >= 100
					&& bot.getAvailableGas() >= 100)
				agent.unit.upgrade(UpgradeType.Charon_Boosters);
			
			return true;
		}
		return false;
	}
}
