/*
* 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.EnemyManager;
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.AttackGroup;
import com.tyr.unitgroups.WorkerGroup;


public class BrieDuCamembert extends CompositeBuildOrder
{
	private ConstantPushTask constantPushTask;
	public boolean attackStarted;
	
	private int armySize = 8;
	private int retreatSize = 0;
	
	private boolean upgradeLegSpeed;
	private boolean detectionNeeded = false;
	private boolean firstAttackDone = false;
	
	private boolean proxyPylonInitialized = true;
	
	@Override
	public void initialize(Game game, Player self, Tyr bot)
	{
		Settings.setRequiredSize(100);
		Settings.setMaximumSize(100);
		Settings.setMaximumWorkers(25);
		Settings.setSmallInvasionDist(480);
		Settings.setLargeInvasionDist(768);
		Settings.setWorkersPerGas(2);
		
		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 = 1;

		bot.taskManager.potentialTasks.add(new ConstantPushTask(DARK_TEMPLAR, ConstantPushSolution.PRIORITIZE));
		constantPushTask = new ConstantPushTask(null, ConstantPushSolution.ATTACK);
		constantPushTask.stop = true;
		bot.taskManager.potentialTasks.add(constantPushTask);
		
		AttackGroup.fearBarracks = true;
		
		ConstantPushTask.prioritizeExpands = true;
		
		BuildAtLocationSolution.removeExcess = false;
		
		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)
		{
			ExpandPart.maximumCcs = 2;
			constantPushTask.stop = false;
			attackStarted = 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) < 4
					&& (count(CYBERNETICS_CORE) > 0)
					&& count(TEMPLAR_ARCHIVES) > 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) >= 5
				&& count(ASSIMILATOR) == 0 || attackStarted)
		{
			bot.spaceManager.build(ASSIMILATOR);
		}
		
		if (minerals() >= 200 
				&& count(CYBERNETICS_CORE) < 1
				&& completed(GATEWAY) > 0
				&& count(ZEALOT) >= 5)
		{
			bot.spaceManager.build(CYBERNETICS_CORE);
		}
		
		if (minerals() >= 150
				&& gas() >= 100
				&& count(CITADEL) == 0
				&& completed(CYBERNETICS_CORE) > 0)
		{
			bot.spaceManager.build(CITADEL);
		}
		
		if (minerals() >= 150
				&& gas() >= 200
				&& count(TEMPLAR_ARCHIVES) < 1
				&& completed(CITADEL) > 0)
		{
			build(TEMPLAR_ARCHIVES);
		}
		
		if (gas() >= 200 && minerals() >= 200
				&& detectionNeeded
				&& count(ROBOTICS_FACILITY) == 0
				&& (count(DRAGOON) >= 5))
		{
			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 BrieDuCamembert 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);
		}
		
		if (count(CANNON) < 4 
				&& minerals() >= 400
				&& completed(FORGE) > 0)
		{
			build(CANNON);
		}
	}
	
	private boolean pauseProduction()
	{
		if (gas() > 250 && minerals() > 400)
			return false;

		if (upgradeLegSpeed && count(CITADEL) == 0)
			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 (count(DARK_TEMPLAR) >= count(DRAGOON) + 5)
				agent.unit.train(DRAGOON);
			if (completed(TEMPLAR_ARCHIVES) > 0)
				agent.unit.train(DARK_TEMPLAR);
			else if (count(ZEALOT) < 5 || minerals() >= 400)
				agent.unit.build(ZEALOT);
			return true;
		}
		else if (agent.unit.getType() == FORGE && !agent.unit.isUpgrading())
		{
			if(pauseProduction())
				return true;
		}
		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);
			return true;
		}
		else if (agent.unit.getType() == CITADEL && !agent.unit.isUpgrading())
		{
			return true;
		}
		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;
	}
}
