/*
* 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 bwapi.Game;
import bwapi.Player;
import bwapi.Position;
import bwapi.UnitType;
import bwapi.UpgradeType;
import com.tyr.DebugMessages;
import com.tyr.Settings;
import com.tyr.Tyr;
import com.tyr.UnitTracker;
import com.tyr.agents.Agent;
import com.tyr.agents.Attack;
import com.tyr.buildingplacement.SpaceManager;
import com.tyr.requirements.ConjRequirement;
import com.tyr.requirements.CostRequirement;
import com.tyr.requirements.Requirement;
import com.tyr.requirements.UnitRequirement;
import com.tyr.tasks.BuildAtLocationSolution;
import com.tyr.tasks.BuildAtLocationTask;
import com.tyr.tasks.ConstantPushSolution;
import com.tyr.tasks.ConstantPushTask;
import com.tyr.unitgroups.WallAttackGroup;
import com.tyr.unitgroups.WorkerGroup;


public class PvIron extends CompositeBuildOrder
{
	private ConstantPushTask constantPushTask;
	public boolean attackStarted;
	
	private int armySize = 15;
	private int retreatSize = 10;
	
	private boolean upgradeLegSpeed;
	private boolean detectionNeeded = false;
	private boolean firstAttackDone = false;
	
	private boolean proxyPylonInitialized = true;
	
	private boolean dtTransition = false;
	
	@Override
	public void initialize(Game game, Player self, Tyr bot)
	{
		Settings.setRequiredSize(100);
		Settings.setMaximumSize(100);
		Settings.setMaximumWorkers(60);
		Settings.setSmallInvasionDist(480);
		Settings.setLargeInvasionDist(768);
		Settings.setWorkersPerGas(3);
		
		Attack.dontWaitAtCannon = true;
		
		this.add(new ExpandPart(true));
		if (game.mapFileName().contains("Alchemist"))
			this.add(new WorkerScoutPart(100));
		else
			this.add(new WorkerScoutPart(1600));
		ExpandPart.maximumCcs = 3;

		bot.taskManager.potentialTasks.add(new ConstantPushTask(DARK_TEMPLAR, ConstantPushSolution.PRIORITIZE));
		constantPushTask = new ConstantPushTask(null, ConstantPushSolution.ATTACK_WALL);
		constantPushTask.stop = true;
		bot.taskManager.potentialTasks.add(constantPushTask);
		
		ConstantPushTask.prioritizeExpands = true;
		
		BuildAtLocationSolution.removeExcess = false;
		WallAttackGroup.fearBarracks = true;
		
		super.initialize(game, self, bot);
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot) 
	{
		DebugMessages.addMessage("Performing PvT build.");
		super.onFrame(game, self, bot);
		

		WorkerGroup.evacuateThreatenedBases = game.getFrameCount() >= 12000;
		
		if (gas() >= 400)
			Settings.setWorkersPerGas(2);
		else if ((gas() < 250 && count(GATEWAY) >= 12) 
				|| gas() + 400 < minerals())
			Settings.setWorkersPerGas(3);
		
		if (constantPushTask != null && completed(ZEALOT) + completed(DRAGOON) <= retreatSize)
			constantPushTask.stop = true;
		if (constantPushTask != null && completed(ZEALOT) + completed(DRAGOON) >= armySize)
		{
			constantPushTask.stop = false;
			attackStarted = true;
		}
		
		if (count(ZEALOT) + count(DRAGOON) >= 10 && count(NEXUS) >= 2)
			detectionNeeded = true;

		if (!firstAttackDone && completed(ZEALOT) + completed(DRAGOON) >= 3)
		{
			constantPushTask.stop = false;
		}
		/*
		if (!firstAttackDone 
				&& EnemyManager.getManager().getAllCount(UnitType.Terran_Siege_Tank_Siege_Mode) > 0)
		{
			constantPushTask.remove();
			firstAttackDone = true;
			constantPushTask.stop = true;
			upgradeLegSpeed = true;
		}
		*/
		
		//if we're running out of supply and have enough minerals ...
		if ((self.supplyTotal() + UnitTracker.getSupplyConstructing() - self.supplyUsed() 
					<= count(GATEWAY)*3 + UnitTracker.getCcCount() * 3)
				&& (minerals() >= 100)
				&& self.supplyTotal() + UnitTracker.getSupplyConstructing() < 400)
		{
			bot.spaceManager.build(PYLON);
		}
		
		//if we've the resources to build a Gateway ...
		if (minerals() >= 150
				&& count(GATEWAY) < 2
				&& completed(PYLON) > 0)
		{
			bot.spaceManager.build(GATEWAY);
		}
		
		if (!pauseProduction())
		{
			if (minerals() >= 150
					&& count(GATEWAY) < 3
					&& count(CYBERNETICS_CORE) > 0)
			{
				bot.spaceManager.build(GATEWAY);
			}
			
			if (count(NEXUS) >= 2
					&& minerals() >= 250
					&& (count(CYBERNETICS_CORE) > 0)
					&& count(GATEWAY) < 8)
			{
				bot.spaceManager.build(GATEWAY);
			}
			
			if (count(NEXUS) >= 2
					&& minerals() >= 150
					&& completed(GATEWAY) >= 8
					&& count(GATEWAY) < 12)
			{
				bot.spaceManager.build(GATEWAY);
			}
		}
		
		if(minerals() >= 100 
				&& UnitTracker.getGeyserCount() > 0
				&& count(GATEWAY) > 0
				&& (count(ZEALOT) >= 4 || dtTransition)
				&& count(ASSIMILATOR) == 0 || attackStarted || dtTransition)
		{
			bot.spaceManager.build(ASSIMILATOR);
		}
		
		if (minerals() >= 200 
				&& count(CYBERNETICS_CORE) < 1
				&& completed(GATEWAY) > 0
				&& count(ZEALOT) >= 4)
		{
			bot.spaceManager.build(CYBERNETICS_CORE);
		}
		
		/*
		if (minerals() >= 150
				&& count(FORGE) < 1
				&& count(NEXUS) >= 2)
		{
			bot.spaceManager.build(FORGE);
		}
		*/
		
		if (minerals() >= 150
				&& gas() >= 100
				&& count(CITADEL) == 0
				&& completed(CYBERNETICS_CORE) > 0
				&& (count(NEXUS) >= 2 || dtTransition)
				&& (count(DRAGOON) + count(ZEALOT) >= 20 || dtTransition)
				&& (completed(SHUTTLE) > 0 || dtTransition))
		{
			bot.spaceManager.build(CITADEL);
		}
		
		if (minerals() >= 150
				&& gas() >= 200
				&& count(TEMPLAR_ARCHIVES) < 1
				&& completed(CITADEL) > 0
				&& (count(NEXUS) >= 3 || dtTransition)
				&& (count(DRAGOON) + count(ZEALOT) >= 25 || dtTransition))
		{
			build(TEMPLAR_ARCHIVES);
		}
		
		if (gas() >= 200 && minerals() >= 200
				&& (detectionNeeded || count(DRAGOON) + count(ZEALOT) >= 10)
				&& count(ROBOTICS_FACILITY) == 0
				&& (count(DRAGOON) >= 5)
				&& (detectionNeeded || count(NEXUS) >= 2))
		{
			bot.spaceManager.build(ROBOTICS_FACILITY);
		}
		
		if (gas() >= 50 && minerals() >= 100
				&& completed(ROBOTICS_FACILITY) > 0
				&& count(OBSERVATORY) == 0
				&& detectionNeeded)
		{
			bot.spaceManager.build(OBSERVATORY);
		}
		
		if (!proxyPylonInitialized && count(ZEALOT) >= 5 && game.getFrameCount() >= 100 && bot.suspectedEnemy.size() == 1)
		{
			proxyPylonInitialized = true;
			final PvIron build = this;
			
			final Position offensivePosition = SpaceManager.getEnemyNatural().getPosition();
				
			final BuildAtLocationTask buildTask = new BuildAtLocationTask(offensivePosition, true);
			buildTask.addBuilding(UnitType.Protoss_Pylon, new ConjRequirement()
				.addRequirement(new CostRequirement(50, 0))
				.addRequirement(new Requirement()
						{
							@Override
							public boolean met()
							{
								return !build.firstAttackDone;
							}
						}));
			buildTask.addBuilding(UnitType.Protoss_Forge, new ConjRequirement()
			.addRequirement(new UnitRequirement(UnitType.Protoss_Pylon, 1, true))
			.addRequirement(new CostRequirement(100, 0))
			.addRequirement(new Requirement()
					{
						@Override
						public boolean met()
						{
							return !build.firstAttackDone;
						}
					}));

		
			for (int i=0; i<4; i++)
			{
				final ConjRequirement requirements = new ConjRequirement()
						.addRequirement(new UnitRequirement(UnitType.Protoss_Forge, 1, true))
						.addRequirement(new CostRequirement(150, 0))
						.addRequirement(new Requirement()
						{
							@Override
							public boolean met()
							{
								return !build.firstAttackDone;
							}
						});
				buildTask.addBuilding(UnitType.Protoss_Photon_Cannon, requirements);
			}
			bot.taskManager.potentialTasks.add(buildTask);
		}
	}
	
	private boolean pauseProduction()
	{
		if (gas() > 250 && minerals() > 400)
			return false;

		if (upgradeLegSpeed && count(CITADEL) == 0
				&& (completed(SHUTTLE) > 0 || dtTransition))
			return true;
		if (count(NEXUS) < 2 && count(DRAGOON) >= 3)
			return true;
		if (count(NEXUS) < 3 && count(DRAGOON) + count(ZEALOT) >= 10)
			return true;
		if (count(CITADEL) == 0
				&& dtTransition)
			return true;
		if (completed(CITADEL) > 0 
				&& !Tyr.self.isUpgrading(UpgradeType.Leg_Enhancements)
				&& Tyr.self.getUpgradeLevel(UpgradeType.Leg_Enhancements) == 0)
			return true;
		if (completed(CITADEL) > 0
				&& count(TEMPLAR_ARCHIVES) == 0)
			return true;
		if (detectionNeeded && count(DRAGOON) >= 5
				&& completed(ROBOTICS_FACILITY) == 1
				&& count(OBSERVATORY) == 0)
			return true;
		if (detectionNeeded && count(DRAGOON) >= 5
				&& completed(OBSERVATORY) == 1
				&& count(OBSERVER) == 0)
			return true;
		if (detectionNeeded && count(DRAGOON) >= 5
				&& count(ROBOTICS_FACILITY) == 0)
			return true;
		if (attackStarted && count(NEXUS) < 3)
			return true;
		return false;
	}
	
	@Override
	public boolean overrideStructureOrder(Game game, Player self, Tyr bot, Agent agent)
	{
		if (agent.unit.getType() == NEXUS)
		{
			if (count(GATEWAY) < 2 && count(PROBE) >= 10)
				return true;
			if (count(ZEALOT) <= 2 && count(PROBE) >= 13)
				return true;
		}
		else if (agent.unit.getType() == GATEWAY && !agent.unit.isTraining())
		{
			if (dtTransition && completed(CYBERNETICS_CORE) > 0 && count(DRAGOON) == 0)
			{
				agent.unit.build(DRAGOON);
			}
			if (dtTransition && gas() >= 75 && count(TEMPLAR_ARCHIVES) > 0 && count(DARK_TEMPLAR) < 2)
				agent.unit.build(DARK_TEMPLAR);
			boolean pause = pauseProduction();
			if (dtTransition && pause)
				return true;
			if (count(ZEALOT) < 4 )
				agent.unit.build(ZEALOT);
			if (pause && minerals() >= 600)
				agent.unit.build(ZEALOT);
			else if (count(ZEALOT) < count(DRAGOON) - 2
					&& minerals() >= 100
					&& (minerals() >= 400 || !pause)
					)
				agent.unit.build(ZEALOT);
			else if (minerals() >= 125 && gas() >= 50)
				agent.unit.build(DRAGOON);
			return true;
		}
		else if (agent.unit.getType() == FORGE && !agent.unit.isUpgrading())
		{
			if(pauseProduction())
				return true;
			if(minerals() >= UpgradeType.Protoss_Ground_Weapons.mineralPrice()
					&& gas() >= UpgradeType.Protoss_Ground_Weapons.gasPrice())
				agent.unit.upgrade(UpgradeType.Protoss_Ground_Weapons);
			
			if(minerals() >= UpgradeType.Protoss_Ground_Armor.mineralPrice()
					&& gas() >= UpgradeType.Protoss_Ground_Armor.gasPrice())
				agent.unit.upgrade(UpgradeType.Protoss_Ground_Armor);
		}
		else if (agent.unit.getType() == CYBERNETICS_CORE && !agent.unit.isUpgrading())
		{
			if(minerals() >= UpgradeType.Singularity_Charge.mineralPrice()
					&& gas() >= UpgradeType.Singularity_Charge.gasPrice()
					&& count(DRAGOON) > 5)
				agent.unit.upgrade(UpgradeType.Singularity_Charge);
		}
		else if (agent.unit.getType() == ROBOTICS_FACILITY)
		{
			if ((count(OBSERVER) < 2)
					&& completed(OBSERVATORY) > 0
					&& minerals() >= 25
					&& gas() >= 75
					&& !agent.unit.isTraining())
				agent.unit.build(OBSERVER);
			else if (count(SHUTTLE) < 4
					&& minerals() >= 200
					&& !agent.unit.isTraining())
				agent.unit.build(SHUTTLE);
			return true;
		}
		else if (agent.unit.getType() == CITADEL && !agent.unit.isUpgrading())
		{
			if (gas() >= UpgradeType.Leg_Enhancements.gasPrice()
					&& minerals() >= UpgradeType.Leg_Enhancements.mineralPrice())
				agent.unit.upgrade(UpgradeType.Leg_Enhancements);
		}
		else if (agent.unit.getType() == TEMPLAR_ARCHIVES && !agent.unit.isResearching())
		{
		}
		else if (agent.unit.getType() == STARGATE)
		{
			if (completed(ARBITER_TRIBUNAL) > 0
					&& minerals() >= 100
					&& gas() >= 350
					&& !agent.unit.isTraining())
				agent.unit.train(ARBITER);
			return true;
		}
		return false;
	}
}
