/*
* 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.EnemyManager;
import com.tyr.Settings;
import com.tyr.Tyr;
import com.tyr.UnitTracker;
import com.tyr.agents.Agent;
import com.tyr.buildingplacement.DefensiveStructures;
import com.tyr.tasks.AssignScience;
import com.tyr.tasks.ExpandPushTask;
import com.tyr.tasks.SalesmenMarinesTask;
import com.tyr.tasks.SiegeNaturalTask;
import com.tyr.unitgroups.MineralWorkers;
import com.tyr.unitgroups.HomeGroup;

import bwapi.Color;
import bwapi.Game;
import bwapi.Player;
import bwapi.Position;
import bwapi.Race;
import bwapi.TechType;
import bwapi.Unit;
import bwapi.UnitType;
import bwapi.UpgradeType;


public class TankContain extends CompositeBuildOrder
{
	/**
	 * Have we reserved minerals and gas to build a science vessel?
	 */
	private boolean reserveScience;
	
	/**
	 * The task used to siege the opponent.
	 */
	private SiegeNaturalTask task = null;
	
	/**
	 * Do we build a bunker?
	 */
	boolean buildBunker;
	
	boolean scienceVessels = true;
	
	int requiredTanks = 10;
	
	boolean enemyTerran = false;
	
	public TankContain() {}
	
	public TankContain(boolean buildBunker, boolean scienceVessels, int requiredTanks) 
	{
		this.buildBunker = buildBunker;
		this.scienceVessels = scienceVessels;
		this.requiredTanks = requiredTanks;
	}
	
	@Override
	public void initialize(Game game, Player self, Tyr bot)
	{
		super.initialize(game, self, bot);
		
		Settings.setWorkersPerGas(3);
		Settings.setRequiredSize(200);
		Settings.setMaximumSize(200);
		Settings.setLargeInvasionDist(850);
		
		this.add(new SupplyDepotPart());
		this.add(new WorkerScoutPart(1600));
		
		ExpandPart.maximumCcs = 1;
		
		bot.taskManager.potentialTasks.add(new AssignScience());
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot) 
	{
		super.onFrame(game, self, bot);
		if (SiegeNaturalTask.done)
			DebugMessages.addMessage("Siege is done.");
		
		if (!enemyTerran)
		{
			for (Unit enemy : EnemyManager.getEnemyUnits())
			{
				if (enemy.getType().getRace() == Race.Terran)
				{
					enemyTerran = true;
					Settings.setRequiredSize(200);
					Settings.setMaximumSize(200);
					HomeGroup.keepTanksSieged = true;
					bot.taskManager.potentialTasks.add(new SalesmenMarinesTask(null, 20, 0, false, 5));
				}
			}
		}
		
		if (task == null && !enemyTerran && (UnitTracker.count(UnitType.Terran_Science_Vessel) > 0 || !scienceVessels))
		{
			task = new SiegeNaturalTask();
			task.requiredTanks = requiredTanks;
			if (enemyTerran)
				bot.taskManager.potentialTasks.add(task);
		}
		
		if (!scienceVessels && UnitTracker.countTanks() >= 15)
		{
			scienceVessels = true;
		}
		
		if (SiegeNaturalTask.done && Settings.getMaximumSize() == 200)
		{
			Settings.setRequiredSize(40);
			Settings.setMaximumSize(60);
		}
		
		if (ExpandPart.maximumCcs == 1 && UnitTracker.countTanks() >= 3)
		{
			this.add(new ExpandPart(true));
			ExpandPart.maximumCcs = 2;
			bot.taskManager.potentialTasks.add(new ExpandPushTask());
		}
		else if (ExpandPart.maximumCcs == 2 && UnitTracker.getCcCount() >= 2 && !enemyTerran)
		{
			int operational = 0;
			for (MineralWorkers workers : bot.workForce.mineralWorkers)
				if (workers.patchWorkers.size() > 0)
					operational++;
			if (operational < 2)
				ExpandPart.maximumCcs = 3;
		}
		else if (ExpandPart.maximumCcs == 2 && UnitTracker.getCcCount() >= 2 && enemyTerran)
		{
			if (UnitTracker.countTanks() 
					+ UnitTracker.count(UnitType.Terran_Vulture)
					+ UnitTracker.count(UnitType.Terran_Goliath)
					+ UnitTracker.count(UnitType.Terran_Marine) >= 40)
				ExpandPart.maximumCcs = 3;
		}
		
		Tyr.drawCircle(new Position(self.getStartLocation().getX()*32 + 64, self.getStartLocation().getY()*32 + 32), Color.Yellow, 64);
		
		//if we've the resources to build a barracks ...
		if(bot.getAvailableMinerals() >= 100 
				&& UnitTracker.count(UnitType.Terran_Barracks) == 0)
		{
			bot.spaceManager.build(UnitType.Terran_Barracks);
		}
		
		if(bot.getAvailableMinerals() >= 150
				&& bot.getAvailableGas() >= 100
				&& (!buildBunker || UnitTracker.getCcCount() >= 2 || UnitTracker.count(UnitType.Terran_Factory) == 0)
				&& (UnitTracker.count(UnitType.Terran_Factory) < 1 || (bot.getAvailableMinerals() >= 250 && bot.getAvailableGas() >= 150))
				&& UnitTracker.count(UnitType.Terran_Barracks) >= 1 
				&& (UnitTracker.count(UnitType.Terran_Factory) < 2 || UnitTracker.count(UnitType.Terran_Academy) > 0)
				&& (UnitTracker.getCcCount() >= 2 || UnitTracker.count(UnitType.Terran_Factory) < 2)
				&& (UnitTracker.count(UnitType.Terran_Starport) > 0 || UnitTracker.count(UnitType.Terran_Factory) < 4 || !scienceVessels)
				&& UnitTracker.count(UnitType.Terran_Factory) < (enemyTerran?7:5)
			)
		{
			bot.spaceManager.build(UnitType.Terran_Factory);
		}
		
		if(UnitTracker.getGeyserCount() > 0 
				&& bot.getAvailableMinerals() >= 100 
				&& (UnitTracker.count(UnitType.Terran_Refinery) == 0 || UnitTracker.count(UnitType.Terran_Factory) >= 1)
				&& UnitTracker.count(UnitType.Terran_Supply_Depot) > 0
				&& UnitTracker.count(UnitType.Terran_Barracks) > 0) 
		{
			bot.spaceManager.build(UnitType.Terran_Refinery);
		}
		
		if (!buildBunker
				&& UnitTracker.countTanks() >= 2
				&& bot.getAvailableMinerals() >= 125
				&& UnitTracker.count(UnitType.Terran_Engineering_Bay) == 0)
		{
			bot.spaceManager.build(UnitType.Terran_Engineering_Bay);
		}
		
		if (UnitTracker.countTanks() >= 4
				&& bot.getAvailableMinerals() >= 150
				&& UnitTracker.count(UnitType.Terran_Academy) == 0)
		{
			bot.spaceManager.build(UnitType.Terran_Academy);
		}
		
		if (scienceVessels
				&& self.completedUnitCount(UnitType.Terran_Factory) >= 4
				&& UnitTracker.count(UnitType.Terran_Starport) == 0
				&& bot.getAvailableGas() >= 100
				&& bot.getAvailableMinerals() >= 150
				&& UnitTracker.getCcCount() >= 2)
		{
			bot.spaceManager.build(UnitType.Terran_Starport);
		}
		
		if (UnitTracker.count(UnitType.Terran_Science_Facility) < 1
				&& (self.completedUnitCount(UnitType.Terran_Starport) > 0 || enemyTerran)
				&& (!enemyTerran || self.completedUnitCount(UnitType.Terran_Armory) >= 2)
				&& bot.getAvailableGas() >= 150
				&& bot.getAvailableMinerals() >= 100)
		{
			bot.spaceManager.build(UnitType.Terran_Science_Facility);
		}
		
		if (bot.getAvailableMinerals() >= 75
				&& self.completedUnitCount(UnitType.Terran_Engineering_Bay) > 0
				&& bot.defensiveStructures.size() >= 2
				&& bot.defensiveStructures.get(1).getUnitCount(UnitType.Terran_Missile_Turret) == 0)
		{
			bot.spaceManager.buildDefensive(UnitType.Terran_Missile_Turret, bot.defensiveStructures.get(1));
		}
		
		if (bot.getAvailableMinerals() >= 75
				&& self.completedUnitCount(UnitType.Terran_Engineering_Bay) > 0
				&& bot.defensiveStructures.size() >= 1
				&& bot.defensiveStructures.get(0).getUnitCount(UnitType.Terran_Missile_Turret) == 0)
		{
			bot.spaceManager.buildDefensive(UnitType.Terran_Missile_Turret, bot.defensiveStructures.get(0));
		}
		
		if ( (UnitTracker.count(UnitType.Terran_Science_Vessel) > 0 || !scienceVessels)
				&& (scienceVessels || UnitTracker.countTanks() >= 5)
				&& UnitTracker.count(UnitType.Terran_Armory) < 2
				&& bot.getAvailableGas() >= 50
				&& bot.getAvailableMinerals() >= 100)
		{
			bot.spaceManager.build(UnitType.Terran_Armory);
		}

		// Build bunkers.
		if (buildBunker
				&& bot.getAvailableMinerals() >= 100
				&& UnitTracker.count(UnitType.Terran_Factory) >= 1
				&& self.completedUnitCount(UnitType.Terran_Barracks) >= 1
				&& UnitTracker.count(UnitType.Terran_Bunker) < 1)
		{
			for(DefensiveStructures structures : bot.defensiveStructures)
			{
				int count = structures.getUnitCount(UnitType.Terran_Bunker);
				
				if(count < 1)
				{
					// We do not build a bunker at our main if there already is one at our natural.
					if (bot.defensiveStructures.size() > 1 && structures.defendedPosition.getDistance(Tyr.tileToPosition(self.getStartLocation())) <= 200)
					{
						if (UnitTracker.count(UnitType.Terran_Bunker) == 0)
							continue;
						else
							break;
					}
					
					bot.spaceManager.buildDefensive(UnitType.Terran_Bunker, structures);
		  			break;
				}
			}
		}
		
	}
	
	@Override
	public boolean overrideStructureOrder(Game game, Player self, Tyr bot,
			Agent agent)
	{
		if (agent.unit.getType() == UnitType.Terran_Barracks)
		{
			if (buildBunker && UnitTracker.count(UnitType.Terran_Factory) == 0)
				return true;
			return UnitTracker.count(UnitType.Terran_Marine) >= 4;
		}
		if (agent.unit.getType() == UnitType.Terran_Factory)
		{
			if (agent.unit.getAddon() != null)
				return false;
			
			if (UnitTracker.usableAddOns(UnitType.Terran_Machine_Shop) == 0)
				return false;
			
			if (UnitTracker.usableAddOns(UnitType.Terran_Machine_Shop) < 2 
					&& UnitTracker.count(UnitType.Terran_Factory) >= (scienceVessels?5:4))
				return false;
			
			if(UnitTracker.count(UnitType.Terran_Armory) >= 1 
					&& !agent.unit.isTraining() 
					&& bot.getAvailableMinerals() >= 100 
					&& bot.getAvailableGas() >= 50
					&& (UnitTracker.count(UnitType.Terran_Goliath) < 4 || bot.getAvailableGas() >= 300))
				agent.unit.train(UnitType.Terran_Goliath);
			else if (Tyr.bot.getAvailableMinerals() >= 75
					&& !agent.unit.isTraining())
				agent.unit.train(UnitType.Terran_Vulture);
			
			return true;
		}
		
		if(agent.unit.getType() == UnitType.Terran_Starport)
		{
			if (agent.unit.isTraining())
				return true;
			
			if (Tyr.game.enemy().getRace() != Race.Protoss)
				return true;
			
			if (agent.unit.getAddon() == null
					&& bot.getAvailableGas() >= 50
					&& bot.getAvailableMinerals() >= 50
					&& UnitTracker.count(UnitType.Terran_Science_Facility) > 0)
				agent.unit.buildAddon(UnitType.Terran_Control_Tower);
			else if (UnitTracker.count(UnitType.Terran_Science_Vessel) < 2
					&& self.completedUnitCount(UnitType.Terran_Science_Facility) > 0)
			{
				if (bot.getAvailableMinerals() >= 100
						&& bot.getAvailableGas() >= 225
						&& !reserveScience)
					agent.unit.train(UnitType.Terran_Science_Vessel);
				else if (!reserveScience)
				{
					reserveScience = true;
					bot.reservedMinerals += 100;
					bot.reservedGas += 225;
				}
				else if (reserveScience
						&& self.minerals() >= 100
						&& self.gas() >= 225)
				{
					agent.unit.train(UnitType.Terran_Science_Vessel);
					reserveScience = false;
					bot.reservedMinerals -= 100;
					bot.reservedGas -= 225;
				}
			}
			return true;
		}
		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 (!agent.unit.isResearching() && self.hasResearched(TechType.Tank_Siege_Mode)
					&& bot.getAvailableMinerals() >= 100
					&& bot.getAvailableGas() >= 100)
				agent.unit.upgrade(UpgradeType.Charon_Boosters);
		}
		
		
		return false;
	}

}
