/*
 * 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.buildingplacement.DefensiveStructures;
import com.tyr.requirements.TechRequirement;
import com.tyr.requirements.UnitRequirement;
import com.tyr.tasks.AssignScience;
import com.tyr.tasks.LocalDefenseTask;
import com.tyr.unitgroups.AttackGroup;

import bwapi.Game;
import bwapi.Player;
import bwapi.TechType;
import bwapi.UnitType;
import bwta.BWTA;

/**
 * Implements a bio build designed to stop Killerbot.
 * 
 * @author Simon
 * 
 */
public class AntiKillMech extends CompositeBuildOrder {
	/**
	 * The minimum size the army needs to be for the first attack.
	 */
	private int minimumArmySize = 30;

	/**
	 * The maximum size the army needs to be for an attack.
	 */
	private int maximumArmySize = 40;

	@Override
	public void initialize(Game game, Player self, Tyr bot) {
		Settings.setRequiredSize(minimumArmySize);
		Settings.setMaximumSize(maximumArmySize);

		Settings.setWorkersPerGas(3);

		this.add(new SupplyDepotPart());
		this.add(new WorkerScoutPart(1600));
		this.add(new ExpandPart(true));
		ExpandPart.maximumCcs = 2;

		this.add(new GenericPartFactory(UnitType.Terran_Barracks)
				.setCost(100, 0)
				.add(new UnitRequirement(UnitType.Terran_Command_Center, 2))
				.create());
		
		GenericPartFactory academyFactory = new GenericPartFactory(
				UnitType.Terran_Academy)
				.add(new UnitRequirement(UnitType.Terran_Barracks))
				.add(new UnitRequirement(UnitType.Terran_Siege_Tank_Tank_Mode))
				.add(new TechRequirement(TechType.Tank_Siege_Mode, false))
				.add(new UnitRequirement(UnitType.Terran_Refinery))
				.add(new UnitRequirement(UnitType.Terran_Command_Center, 2));
		this.add(academyFactory.create());

		this.add(new GenericPartFactory(UnitType.Terran_Engineering_Bay).add(
				new UnitRequirement(UnitType.Terran_Factory)).create());
		
		this.add(new GenericPartFactory(UnitType.Terran_Armory)
			.add(new UnitRequirement(UnitType.Terran_Siege_Tank_Tank_Mode))
			.add(new TechRequirement(TechType.Tank_Siege_Mode, false)).create());

		this.add(new GenericPartFactory(UnitType.Terran_Factory).setMax(2)
				.setCost(150, 75)
				.add(new UnitRequirement(UnitType.Terran_Barracks, 1, true))
				.add(new UnitRequirement(UnitType.Terran_Command_Center, 2))
				.create());
		
		this.add(new GenericPartFactory(UnitType.Terran_Factory).setMax(6)
				.setCost(150, 75)
				.add(new UnitRequirement(UnitType.Terran_Siege_Tank_Tank_Mode, 2))
				.add(new TechRequirement(TechType.Tank_Siege_Mode, false))
				.create());

		
		this.add(new GenericPartFactory(UnitType.Terran_Starport)
				.add(new UnitRequirement(UnitType.Terran_Engineering_Bay))
				.add(new UnitRequirement(UnitType.Terran_Factory, 4)).create());

		this.add(new GenericPartFactory(UnitType.Terran_Science_Facility)
				.add(new UnitRequirement(UnitType.Terran_Engineering_Bay))
				.add(new UnitRequirement(UnitType.Terran_Starport, 1, true))
				.create());

		
		LocalDefenseTask localDefenseTask = new LocalDefenseTask(BWTA.getRegion(self.getStartLocation()), 3);
		bot.taskManager.potentialTasks.add(localDefenseTask);
		bot.taskManager.potentialTasks.add(new AssignScience());
		AttackGroup.fearLurkers = true;

		super.initialize(game, self, bot);
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot) {
		DebugMessages.addMessage("Going bio.");

		StopWatch watch = new StopWatch();
		long time;
		watch.start();

		super.onFrame(game, self, bot);
		
		if (self.completedUnitCount(UnitType.Terran_Vulture) + self.completedUnitCount(UnitType.Terran_Goliath) + self.completedUnitCount(UnitType.Terran_Siege_Tank_Siege_Mode) + self.completedUnitCount(UnitType.Terran_Siege_Tank_Tank_Mode) >= 30)
		{
			ExpandPart.maximumCcs = 3;
		}

		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Bio super time: " + time);

		if (UnitTracker.count(UnitType.Terran_Factory) > 3
				&& bot.getAvailableGas() < 400)
			Settings.setWorkersPerGas(3);
		else if (UnitTracker.count(UnitType.Terran_Factory) > 0
				|| UnitTracker.count(UnitType.Terran_Engineering_Bay) > 0)
			Settings.setWorkersPerGas(2);

		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Bio tier 1 time: " + time);

		if (bot.getAvailableMinerals() >= 100
				&& UnitTracker.getGeyserCount() > 0
				&& UnitTracker.count(UnitType.Terran_Command_Center) >= 2
				&& (UnitTracker.count(UnitType.Terran_Refinery) == 0 || UnitTracker
						.count(UnitType.Terran_Factory) > 0)) {
			bot.spaceManager.build(UnitType.Terran_Refinery);
		}

		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Bio refinery: " + time + " geyserCount: "
					+ UnitTracker.getGeyserCount());


		
		// Build bunkers.
		if (bot.getAvailableMinerals() >= 50 
				&& (bot.getAvailableMinerals() >= 100 || UnitTracker.count(UnitType.Terran_Factory) > 1)
				&& (UnitTracker.count(UnitType.Terran_Factory) >= 1) 
				&& self.completedUnitCount(UnitType.Terran_Barracks) >= 1
				&& UnitTracker.count(UnitType.Terran_Bunker) < 2
				&& (UnitTracker.count(UnitType.Terran_Bunker) == 0 || UnitTracker.countTanks() > 0))
		{
			for(DefensiveStructures structures : bot.defensiveStructures)
			{
				int count = structures.getUnitCount(UnitType.Terran_Bunker);
				
				if(count < 2)
				{
					// We do not build a bunker at our main if there already is one at our natural.
					if (structures.defendedPosition.getDistance(Tyr.tileToPosition(self.getStartLocation())) <= 200)
						continue;
					
					bot.spaceManager.buildDefensive(UnitType.Terran_Bunker, structures);
		  			break;
				}
			}
		}

		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Bio bunker time: " + time);

		if(UnitTracker.count(UnitType.Terran_Engineering_Bay) >= 1 && bot.getAvailableMinerals() >= 75)
		{
			for(DefensiveStructures structures : bot.defensiveStructures)
			{
				int count = structures.getUnitCount(UnitType.Terran_Missile_Turret);
				
				if(count < 2 && structures.defences.size() > 0)
				{
		  			bot.spaceManager.buildDefensive(UnitType.Terran_Missile_Turret, structures);
		  			break;
				}
			}
		}

		time = watch.time();
		if (time > 55)
			DebugMessages.addMessage("Bio turrets 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)
		{
			if (UnitTracker.count(UnitType.Terran_Command_Center) < 2 && bot.getAvailableMinerals() < 400)
				return true;
			
			if ((UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) + UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) == 0
					|| (!self.isResearching(TechType.Tank_Siege_Mode) && !self.hasResearched(TechType.Tank_Siege_Mode)))
					&& bot.getAvailableMinerals() < 200
					&& (UnitTracker.count(UnitType.Terran_Marine) >= 5 || bot.getAvailableMinerals() >= 300)
				)
				return true;
		}
		else if (agent.unit.getType() == UnitType.Terran_Academy)
		{
			return true;
		}
		else if (agent.unit.getType() == UnitType.Terran_Starport)
		{
			if (UnitTracker.count(UnitType.Terran_Command_Center) < 2 && bot.getAvailableMinerals() < 400)
				return true;
			if (UnitTracker.count(UnitType.Terran_Science_Vessel) >= 2 && UnitTracker.countTanks() >= 4 && UnitTracker.count(UnitType.Terran_Armory) == 0)
				return true;
			if (agent.unit.getAddon() != null)
			{
				if (!agent.unit.isTraining()
						&& UnitTracker.count(UnitType.Terran_Science_Facility) >0
						&& bot.getAvailableMinerals() >= 100 
						&& bot.getAvailableGas() >= 225)
					agent.unit.train(UnitType.Terran_Science_Vessel);
				return true;
			}
			
			if (UnitTracker.count(UnitType.Terran_Control_Tower) == 0)
			{
				if (UnitTracker.count(UnitType.Terran_Science_Facility) > 0
						&& bot.getAvailableMinerals() >= 50 && bot.getAvailableGas() >= 50)
					agent.unit.buildAddon(UnitType.Terran_Control_Tower);
				return true;
			}
			
			return UnitTracker.count(UnitType.Terran_Science_Vessel) == 0;
		}
		else if (agent.unit.getType() == UnitType.Terran_Factory)
		{
			if (UnitTracker.count(UnitType.Terran_Command_Center) < 2 && bot.getAvailableMinerals() < 400)
				return true;
			if (UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) + UnitTracker.count(UnitType.Terran_Siege_Tank_Tank_Mode) < 2)
				return false;
			if (!self.hasResearched(TechType.Irradiate)
					&& bot.getAvailableGas() < 350
					&& UnitTracker.countTanks() >= 4)
				return true;



			if(self.completedUnitCount(UnitType.Terran_Armory) >= 1 && !agent.unit.isTraining()
					&& UnitTracker.count(UnitType.Terran_Siege_Tank_Siege_Mode) + UnitTracker.count(UnitType.Terran_Siege_Tank_Tank_Mode) 
						>= 5 + (UnitTracker.count(UnitType.Terran_Goliath)/2) 
					&& bot.getAvailableMinerals() >= 100 && bot.getAvailableGas() >= 50)
			{
				agent.unit.train(UnitType.Terran_Goliath);
				return true;
			}
			else 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)
			{
				agent.unit.train(UnitType.Terran_Vulture);
				return true;
			}
			
			return false;
		}
		else if (agent.unit.getType() == UnitType.Terran_Science_Facility)
		{
			if (!self.hasResearched(TechType.Irradiate)
					&& bot.getAvailableMinerals() >= 200 
					&& bot.getAvailableGas() >= 200
					&& UnitTracker.count(UnitType.Terran_Science_Vessel) > 0)
			{
				agent.unit.research(TechType.Irradiate);
				return true;
			}
			return false;
		}
		else if (agent.unit.getType() == UnitType.Terran_Engineering_Bay)
		{
			return true;
		}
		
		return false;
	}
}
