/*
* 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 java.util.ArrayList;

import bwapi.Game;
import bwapi.Player;
import bwapi.Position;
import bwapi.Race;
import bwapi.Unit;
import bwapi.UnitType;
import bwapi.UpgradeType;
import bwta.BWTA;

import com.tyr.EnemyManager;
import com.tyr.EnemyPosition;
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.UnitRequirement;
import com.tyr.tasks.BuildAtLocationTask;
import com.tyr.tasks.ClearExpandsTask;
import com.tyr.tasks.ConstantPushSolution;
import com.tyr.tasks.ConstantPushTask;
import com.tyr.tasks.LocalDefenseTask;


public class DragoonPush extends CompositeBuildOrder
{
	private ConstantPushTask constantPushTask;
	private LocalDefenseTask localDefenseTask;
	private LocalDefenseTask thirdDefenseTask;
	private ClearExpandsTask clearExpandsTask;
	private boolean cannonDefense;
	private boolean earlyZealots;
	private boolean takeExpands;
	private boolean twoGateOpener;
	private boolean defensesInitialized;
	private boolean expandFirst = true;
	private boolean detectionNeeded;
	public boolean attackStarted;
	private boolean upgradeLegSpeed;
	private boolean clearExpands;
	private boolean buildReaver = false;

	private Race opponentRace = Race.Unknown;
	
	private int armySize = 25;
	private int retreatSize = 10;
	
	public DragoonPush(int armySize, boolean cannonDefense, boolean detectionNeeded, boolean earlyZealots, boolean takeExpands, boolean twoGateOpener, boolean clearExpands, boolean buildReaver)
	{
		this.armySize = armySize;
		this.cannonDefense = cannonDefense;
		defensesInitialized = !cannonDefense;
		this.detectionNeeded = detectionNeeded;
		this.earlyZealots = earlyZealots;
		this.takeExpands = takeExpands;
		this.twoGateOpener = twoGateOpener;
		this.clearExpands = clearExpands;
		this.buildReaver = buildReaver;
	}
	
	public DragoonPush(int armySize, int retreatSize, boolean cannonDefense, boolean detectionNeeded, boolean earlyZealots, boolean takeExpands, boolean twoGateOpener, boolean clearExpands, boolean buildReaver)
	{
		this.armySize = armySize;
		this.retreatSize = retreatSize;
		this.cannonDefense = cannonDefense;
		defensesInitialized = !cannonDefense;
		this.detectionNeeded = detectionNeeded;
		this.earlyZealots = earlyZealots;
		this.takeExpands = takeExpands;
		this.twoGateOpener = twoGateOpener;
		this.clearExpands = clearExpands;
		this.buildReaver = buildReaver;
	}
	
	@Override
	public void initialize(Game game, Player self, Tyr bot)
	{
		Settings.setRequiredSize(100);
		Settings.setMaximumSize(100);
		Settings.setMaximumWorkers(40);
		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 = 2;
		
		localDefenseTask = new LocalDefenseTask(BWTA.getRegion(self.getStartLocation()), 0);
		bot.taskManager.potentialTasks.add(localDefenseTask);
		
		thirdDefenseTask = new LocalDefenseTask(null, 0);
		bot.taskManager.potentialTasks.add(thirdDefenseTask);
		constantPushTask = new ConstantPushTask(null, ConstantPushSolution.ATTACK);
		constantPushTask.stop = true;
		clearExpandsTask = new ClearExpandsTask();
		bot.taskManager.potentialTasks.add(clearExpandsTask);
		bot.taskManager.potentialTasks.add(constantPushTask);
		
		ConstantPushTask.prioritizeExpands = true;
		
		super.initialize(game, self, bot);
	}
	
	private Position getDefensivePosition()
	{
		final Position location = SpaceManager.getNatural();
		if (location == null)
			return null;
	
		ArrayList<Position> minerals = new ArrayList<Position>();
		// Find all the mineral patches close to the base.
		for (EnemyPosition neutralUnit : EnemyManager.getManager().neutralBuildingMemory)
			if (neutralUnit.type.isMineralField() && neutralUnit.pos.getDistance(location) <= 270)
	        	minerals.add(neutralUnit.pos);
	        
		return SpaceManager.getDefensePosPositions(location, minerals);
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot) 
	{
		super.onFrame(game, self, bot);
		
		if (opponentRace == Race.Unknown)
		{
			/*
			if (game.enemy().getRace() == Race.Zerg)
				opponentRace = Race.Zerg;
			else if (game.enemy().getRace() == Race.Terran)
				opponentRace = Race.Terran;
			else if (game.enemy().getRace() == Race.Protoss)
				opponentRace = Race.Protoss;
				*/
			if (opponentRace == Race.Unknown)
			{
				for (Unit unit : EnemyManager.getEnemyUnits())
				{
					if (unit.getType().getRace() == Race.Zerg)
						opponentRace = Race.Zerg;
					else if (unit.getType().getRace() == Race.Terran)
						opponentRace = Race.Terran;
					else if (unit.getType().getRace() == Race.Protoss)
						opponentRace = Race.Protoss;
					
					if (opponentRace != Race.Unknown)
						break;
				}
			}
		}
		
		if (twoGateOpener
				&& count(ZEALOT) < 6)
		{
			Settings.setWorkersPerGas(3);
			
			//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))
			{
				bot.spaceManager.build(PYLON);
			}
			
			//if we've the resources to build a Gateway ...
			if (minerals() >= 150
					&& count(GATEWAY) == 0
					&& completed(PYLON) > 0)
			{
				bot.spaceManager.build(GATEWAY);
			}
			
			//if we've the resources to build a Gateway ...
			if (minerals() >= 150
					&& count(GATEWAY) < 2)
			{
				bot.spaceManager.build(GATEWAY);
			}
			
			return;
		}
		
		if (clearExpands)
		{
			if (completed(ZEALOT) + completed(DRAGOON) >= armySize + 1)
				clearExpandsTask.setActive(true);
			if (completed(ZEALOT) + completed(DRAGOON) <= armySize - 5)
				clearExpandsTask.setActive(false);
		}
		
		if (!defensesInitialized && game.getFrameCount() >= 100)
		{
			final Position defensivePosition = getDefensivePosition();
			if (defensivePosition != null)
				initializeDefenses(defensivePosition);
		}
		
		if (gas() >= 400)
			Settings.setWorkersPerGas(2);
		else if ((gas() < 250 && count(GATEWAY) >= 12) 
				|| gas() + 400 < minerals())
			Settings.setWorkersPerGas(3);
		
		if (twoGateOpener
				&& (self.getUpgradeLevel(UpgradeType.Leg_Enhancements) > 0 
						|| EnemyManager.getManager().getEnemyTypes().contains(SCARAB)))
			armySize = 20;

		if (constantPushTask != null && completed(ZEALOT) + completed(DRAGOON) <= retreatSize)
			constantPushTask.stop = true;
		if (constantPushTask != null && completed(ZEALOT) + completed(DRAGOON) >= armySize)
		{
			constantPushTask.stop = false;
			attackStarted = true;
			localDefenseTask.setDefendersNeeded(3);
			if (takeExpands)
				ExpandPart.maximumCcs = 100;
			if (opponentRace == Race.Zerg || opponentRace == Race.Unknown)
				detectionNeeded = true;
		}
		
		if (thirdDefenseTask.getDefendersNeeded() == 0 && Tyr.bot.workForce.mineralWorkers.size() >= 3)
		{
			thirdDefenseTask.setDefendersNeeded(3);
			thirdDefenseTask.setDefendedPosition(Tyr.bot.workForce.mineralWorkers.get(2).resourceDepot.getPosition());
		}
		
		if (completed(ZEALOT) + completed(DRAGOON) >= 9)
			upgradeLegSpeed = true;
			
		if (EnemyManager.getManager().getEnemyTypes().contains(DARK_TEMPLAR)
				|| EnemyManager.getManager().getEnemyTypes().contains(UnitType.Zerg_Lurker))
			detectionNeeded = 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
				&& (!cannonDefense || count(PYLON) > 0))
		{
			bot.spaceManager.build(PYLON);
		}
		
		//if we've the resources to build a Gateway ...
		if ((count(NEXUS) >= 2 || !expandFirst)
				&& minerals() >= 150
				&& count(GATEWAY) == 0
				&& completed(PYLON) > 0
				&& count(PYLON) > 0)
		{
			bot.spaceManager.build(GATEWAY);
		}
		
		//if we've the resources to build a Gateway ...
		if ((count(NEXUS) >= 2 || !expandFirst)
				&& (count(NEXUS) >= 2 || minerals() >= 500 || !expandFirst)
				&& minerals() >= 150
				&& count(GATEWAY) < 2
				&& count(CYBERNETICS_CORE) > 0)
		{
			bot.spaceManager.build(GATEWAY);
		}
		
		if (!pauseProduction())
		{
			if ((count(NEXUS) >= 2 || !expandFirst)
					&& minerals() >= 250
					&& count(GATEWAY) < 4
					&& (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(NEXUS) >= 2 || !expandFirst))
		{
			bot.spaceManager.build(ASSIMILATOR);
		}
		
		if (minerals() >= 200 
				&& count(CYBERNETICS_CORE) < 1
				&& completed(GATEWAY) > 0
				&& (count(NEXUS) >= 2 || !expandFirst))
		{
			bot.spaceManager.build(CYBERNETICS_CORE);
		}
		
		if (gas() >= 200 && minerals() >= 200
				&& (count(GATEWAY) >= 8 || detectionNeeded || buildReaver)
				&& count(ROBOTICS_FACILITY) == 0
				&& (count(DRAGOON) >= 5 || buildReaver))
		{
			bot.spaceManager.build(ROBOTICS_FACILITY);
		}
		
		if (gas() >= 50 && minerals() >= 100
				&& completed(ROBOTICS_FACILITY) > 0
				&& count(OBSERVATORY) == 0
				&& detectionNeeded)
		{
			bot.spaceManager.build(OBSERVATORY);
		}
		
		if (minerals() >= 150
				&& count(FORGE) < 2
				&& count(DRAGOON) >= 2
				&& (!buildReaver || count(REAVER) > 0))
		{
			bot.spaceManager.build(FORGE);
		}
		
		if (upgradeLegSpeed 
				&& minerals() >= 150
				&& gas() >= 100
				&& count(CITADEL) == 0
				&& completed(CYBERNETICS_CORE) > 0
				&& count(NEXUS) >= 2
				&& (!buildReaver || count(REAVER) > 0))
		{
			bot.spaceManager.build(CITADEL);
		}
		
		if (bot.getAvailableGas() >= 100 && bot.getAvailableMinerals() >= 150
				&& self.completedUnitCount(UnitType.Protoss_Robotics_Facility) > 0
				&& UnitTracker.count(UnitType.Protoss_Robotics_Support_Bay) == 0
				&& buildReaver)
		{
			bot.spaceManager.build(UnitType.Protoss_Robotics_Support_Bay);
		}
		
		/*
		if (minerals() >= 400
				&& gas() >= 400
				&& count(TEMPLAR_ARCHIVES) < 1
				&& completed(CITADEL) > 0
				&& count(NEXUS) >= 3)
		{
			bot.spaceManager.build(TEMPLAR_ARCHIVES);
		}*/
	}
	
	private void initializeDefenses(Position defensivePosition)
	{
		defensesInitialized = true;
			
		BuildAtLocationTask buildTask = new BuildAtLocationTask(defensivePosition, true);
		buildTask.addBuilding(PYLON, new UnitRequirement(PROBE, 7));
		buildTask.addBuilding(FORGE, new ConjRequirement()
			.addRequirement(new UnitRequirement(PYLON, 1, true))
			.addRequirement(new CostRequirement(100, 0)));
		buildTask.addBuilding(CANNON, new ConjRequirement()
		.addRequirement(new UnitRequirement(FORGE, 1, true))
		.addRequirement(new CostRequirement(150, 0)));
		if (earlyZealots)
		{
			buildTask.addBuilding(GATEWAY, new ConjRequirement()
			.addRequirement(new CostRequirement(150, 0)));
		}
		else
		{
			buildTask.addBuilding(GATEWAY, new ConjRequirement()
			.addRequirement(new CostRequirement(150, 0))
			.addRequirement(new UnitRequirement(NEXUS, 2, true)));
		}
		Tyr.bot.taskManager.potentialTasks.add(buildTask);
	}
	
	private boolean pauseProduction()
	{
		if (gas() > 250 && minerals() > 400)
			return false;

		if (upgradeLegSpeed && count(CITADEL) == 0
				&& (!buildReaver || count(REAVER) > 0))
			return true;
		if (completed(CITADEL) > 0 
				&& !Tyr.self.isUpgrading(UpgradeType.Leg_Enhancements)
				&& Tyr.self.getUpgradeLevel(UpgradeType.Leg_Enhancements) == 0)
			return true;
		if (detectionNeeded && count(DRAGOON) >= 5
				&& count(ROBOTICS_FACILITY) == 0)
			return true;
		if (buildReaver && count(GATEWAY) >= 3
				&& completed(CYBERNETICS_CORE) > 0
				&& count(ROBOTICS_FACILITY) == 0
				 && count(DRAGOON) >= 2)
			return true;
		if (buildReaver && completed(ROBOTICS_FACILITY) > 0
				&& count(ROBO_SUPPORT) == 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 (buildReaver 
				&& count(REAVER) == completed(REAVER)
				&& count(REAVER) < 3
				&& completed(ROBO_SUPPORT) > 0
				&& completed(ROBOTICS_FACILITY) > 0)
			return true;
		if (takeExpands && attackStarted && count(NEXUS) < 3)
			return true;
		return false;
	}
	
	@Override
	public boolean overrideStructureOrder(Game game, Player self, Tyr bot, Agent agent)
	{
		if (agent.unit.getType() == GATEWAY && !agent.unit.isTraining())
		{
			if (twoGateOpener && count(ZEALOT) < 6
					&& minerals() >= 100)
				agent.unit.build(ZEALOT);
			boolean pause = pauseProduction();
			if (earlyZealots
					&& completed(CYBERNETICS_CORE) == 0
					&& minerals() >= 100)
				agent.unit.build(ZEALOT);
			if (count(ZEALOT) < count(DRAGOON) - 5
					&& minerals() >= 100
					&& (minerals() >= 400 || !pause)
					)
				agent.unit.build(ZEALOT);
			else if (minerals() >= 125 && gas() >= 50
					&& ((minerals() >= 400 && gas() > 200) || !pause))
				agent.unit.build(DRAGOON);
			return true;
		}
		else if (agent.unit.getType() == FORGE && !agent.unit.isUpgrading())
		{
			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()
					&& (!buildReaver || 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()
					&& (!buildReaver || count(REAVER) > 0))
				agent.unit.build(OBSERVER);
			else if (!agent.unit.isTraining()
					&& bot.getAvailableMinerals() >= 200
					&& bot.getAvailableGas() >= 100
					&& buildReaver)
				agent.unit.build(UnitType.Protoss_Reaver);
			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);
		}
		return false;
	}
}
