/*
* 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 java.util.Comparator;
import java.util.List;
import com.tyr.BWTAProxy;
import com.tyr.EnemyManager;
import com.tyr.PositionUtil;
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.BuildAtLocationTask;
import com.tyr.tasks.CannonDefenseTask;
import com.tyr.tasks.ConstantPushTask;
import com.tyr.tasks.DestroyBuildingsTask;

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


public class CannonWall extends CompositeBuildOrder
{
	boolean fastExpand = true;
	boolean defensesInitialized = false;
	boolean attackStarted = false;
	boolean reavers = false;
	private int cannonCount;
	
	private ConstantPushTask constantPushTask;
	
	private boolean detectionNeeded = false;
	private boolean limitZealots;
	
	private boolean proxyCannons = false;
	private boolean cannonDefense = true;
	
	boolean workerRush;
	private boolean dragoonOnly;
	private boolean doNotExpand;
	
	public CannonWall()
	{
		this(false);
	}
	
	public CannonWall(boolean fastExpand)
	{
		this(fastExpand, fastExpand?6:4);
	}
	
	public CannonWall(boolean fastExpand, int cannonCount)
	{
		this.fastExpand = fastExpand;
		this.cannonCount = cannonCount;
	}
	
	public CannonWall(boolean fastExpand, int cannonCount, boolean reavers)
	{
		this.fastExpand = fastExpand;
		this.cannonCount = cannonCount;
		this.reavers = reavers;
	}
	
	public CannonWall(boolean fastExpand, int cannonCount, boolean reavers, boolean limitZealots)
	{
		this.fastExpand = fastExpand;
		this.cannonCount = cannonCount;
		this.reavers = reavers;
		this.limitZealots = limitZealots;
	}
	
	@Override
	public void initialize(Game game, Player self, Tyr bot)
	{
		Settings.setRequiredSize(100);
		Settings.setMaximumSize(100);
		Settings.setSmallInvasionDist(480);
		Settings.setLargeInvasionDist(640);
		Attack.dontWaitAtCannon = true;
		
		this.add(new ExpandPart(true));
		ExpandPart.maximumCcs = fastExpand?2:1;
		if (game.mapFileName().contains("Alchemist") || proxyCannons)
			this.add(new WorkerScoutPart(100));
		else
			this.add(new WorkerScoutPart(1600));

		if (cannonDefense)
			bot.taskManager.potentialTasks.add(new CannonDefenseTask());
		
		super.initialize(game, self, bot);
	}
	
	public CannonWall noCannonDefense()
	{
		cannonDefense = false;
		return this;
	}
	
	private Position getDefensivePosition()
	{
		if (proxyCannons)
		{
			return SpaceManager.getEnemyNatural().getPosition();
		}
		else if (fastExpand)
			return SpaceManager.getNaturalDefensePos();
		else
		{
			final Position startLocation = Tyr.tileToPosition(Tyr.self.getStartLocation());
			final Position mainExit = SpaceManager.getMainExit();
			return new Position((startLocation.getX() + mainExit.getX())/2, (startLocation.getY() + mainExit.getY())/2);
		}
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot) 
	{
		super.onFrame(game, self, bot);
		
		if (UnitTracker.count(UnitType.Protoss_Gateway) >= 3)
			Settings.setWorkersPerGas(3);
		
		if (bot.getAvailableMinerals() < 400 
				&& UnitTracker.count(UnitType.Protoss_Photon_Cannon) < Math.min(3, cannonCount)
				&& count(NEXUS) == 1)
		{
			if (UnitTracker.count(UnitType.Protoss_Pylon) == 0)
				Settings.setMaximumWorkers(7);
			else
				Settings.setMaximumWorkers(6);
		}
		else
			Settings.setMaximumWorkers(40);

		if (!workerRush && EnemyManager.getManager().getAllCount(MARINE) < 5)
		{
			int count = 0;
			for (Unit unit : EnemyManager.getEnemyUnits())
				if (unit.getType().isWorker()
						&& PositionUtil.distanceSq(unit, Tyr.tileToPosition(self.getStartLocation())) <= Settings.getLargeInvasionDist() * Settings.getLargeInvasionDist())
					count++;
			
			if (count >= 3)
				workerRush = true;
		}
			
		if (EnemyManager.getManager().getEnemyTypes().contains(UnitType.Protoss_Dark_Templar) ||EnemyManager.getManager().getEnemyTypes().contains(UnitType.Zerg_Lurker))
			detectionNeeded = true;
		
		if (!attackStarted && bot.homeGroup.units.size() >= (fastExpand?30:20))
		{
			attackStarted = true;
			
			if (fastExpand)
			{
				List<Unit> targets = new ArrayList<Unit>();
				for (Unit unit : self.getUnits())
					if (unit.getType() == UnitType.Protoss_Photon_Cannon)
						targets.add(unit);
				
				DestroyBuildingsTask destroyBuildingsTask = new DestroyBuildingsTask(targets);
				
				if (targets.size() > 0)
					bot.taskManager.potentialTasks.add(destroyBuildingsTask);
			}
			
			constantPushTask = new ConstantPushTask(null);
			bot.taskManager.potentialTasks.add(constantPushTask);
			if (!doNotExpand)
				ExpandPart.maximumCcs = 100;
			BuildAtLocationTask.stop = true;
		}
			
		if (constantPushTask != null && self.completedUnitCount(UnitType.Protoss_Zealot) + self.completedUnitCount(UnitType.Protoss_Dragoon) <= 10)
			constantPushTask.stop = true;
		if (constantPushTask != null && self.completedUnitCount(UnitType.Protoss_Zealot) + self.completedUnitCount(UnitType.Protoss_Dragoon) >= 20)
			constantPushTask.stop = false;

		if (!defensesInitialized && game.getFrameCount() >= 100 && !Tyr.game.mapFileName().contains("Alchemist") && (!proxyCannons || bot.suspectedEnemy.size() == 1))
		{
			defensesInitialized = true;
			final CannonWall build = this;
			
			final Position defensivePosition = getDefensivePosition();
				
			final BuildAtLocationTask buildTask = new BuildAtLocationTask(defensivePosition, true);
			buildTask.addBuilding(UnitType.Protoss_Pylon, new UnitRequirement(UnitType.Protoss_Probe, 7));
			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.workerRush || completed(ZEALOT) > 0;
							}
						}));

			
			for (int i=0; i<cannonCount; 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.workerRush || completed(ZEALOT) > 0;
							}
						});
				if (i >= 4)
					requirements.addRequirement(new UnitRequirement(NEXUS, 2));
				buildTask.addBuilding(UnitType.Protoss_Photon_Cannon, requirements);
			}
			
			bot.taskManager.potentialTasks.add(buildTask);
		}

		if (!defensesInitialized
				&& game.getFrameCount() >= 100
				&& Tyr.game.mapFileName().contains("Alchemist")
				&& bot.suspectedEnemy.size() == 1)
		{
			defensesInitialized = true;
			
			Position closestChoke= null;
			int dist = Integer.MAX_VALUE;

			final Position enemyMain = bot.suspectedEnemy.get(0).getPosition();

			final Position main = Tyr.getStartLocation();
			final Position pos;
			if (!fastExpand)
			{
				for (Chokepoint choke : BWTAProxy.getRegion(main).getChokepoints())
				{
					final int newDist = PositionUtil.distanceSq(choke.getCenter(), enemyMain); 
					if (newDist < dist)
					{
						dist = newDist;
						closestChoke = choke.getCenter();
					}
				}
				pos = PositionUtil.getWeighted(main, closestChoke, 0.7);
			}
			else
			{
				List<Position> bases = new ArrayList<>();
				for (BaseLocation base : bot.expands)
					if (PositionUtil.distanceSq(base.getPosition(), main) >= 100 * 100)
						bases.add(base.getPosition());
				bases.sort(new Comparator<Position>()
				{
					@Override
					public int compare(Position p1, Position p2)
					{
						return PositionUtil.distanceSq(main, p1) - PositionUtil.distanceSq(main, p2);
					}
				});
				
				pos = SpaceManager.getNaturalDefensePos();
			}
			final BuildAtLocationTask buildTask = new BuildAtLocationTask(pos, true);
			
			final ConjRequirement pylonReq = new ConjRequirement()
				.addRequirement(new UnitRequirement(UnitType.Protoss_Probe, 7));
			buildTask.addBuilding(UnitType.Protoss_Pylon, pylonReq);
			buildTask.addBuilding(UnitType.Protoss_Forge, new ConjRequirement()
				.addRequirement(new UnitRequirement(UnitType.Protoss_Pylon, 1, true))
				.addRequirement(new CostRequirement(100, 0)));
			for (int i=0; i<cannonCount; i++)
				buildTask.addBuilding(UnitType.Protoss_Photon_Cannon, new ConjRequirement()
					.addRequirement(new UnitRequirement(UnitType.Protoss_Forge, 1, true))
					.addRequirement(new CostRequirement(150, 0)));
			bot.taskManager.potentialTasks.add(buildTask);
		}
		
		// If we have no power to build any buildings, build another pylon. 
		if (SpaceManager.noPower && (bot.getAvailableMinerals() >= 100)
				&& UnitTracker.count(UnitType.Protoss_Pylon) == self.completedUnitCount(UnitType.Protoss_Pylon)
				&& UnitTracker.count(UnitType.Protoss_Pylon) >= 1
				&& (UnitTracker.count(UnitType.Protoss_Photon_Cannon) >= Math.min(3, cannonCount) || bot.getAvailableMinerals() >= 250))
		{
			bot.spaceManager.build(UnitType.Protoss_Pylon);
		}
		
		//if we're running out of supply and have enough minerals ...
		if ((self.supplyTotal() + UnitTracker.getSupplyConstructing() - self.supplyUsed() 
					<= UnitTracker.count(UnitType.Protoss_Gateway)*3 + UnitTracker.getCcCount() * 3)
				&& (bot.getAvailableMinerals() >= 100)
				&& self.supplyTotal() + UnitTracker.getSupplyConstructing() < 400
				&& UnitTracker.count(UnitType.Protoss_Pylon) >= 1
				&& (UnitTracker.count(UnitType.Protoss_Photon_Cannon) >= Math.min(3, cannonCount) || bot.getAvailableMinerals() >= 250))
		{
			bot.spaceManager.build(UnitType.Protoss_Pylon);
		}
		
		//if we've the resources to build a Gateway ...
		if ((UnitTracker.count(UnitType.Protoss_Photon_Cannon) >= Math.min(4, cannonCount) || workerRush)
				&& (UnitTracker.count(UnitType.Protoss_Nexus) >= 2 || bot.getAvailableMinerals() >= 500 || !fastExpand)
				&& bot.getAvailableMinerals() >= 150
						&& (count(GATEWAY) == 0 || count(CYBERNETICS_CORE) > 0 || game.enemy().getRace() != Race.Zerg)
						&& (count(GATEWAY) == 0 || count(CYBERNETICS_CORE) > 0 || !limitZealots)
				&& UnitTracker.count(UnitType.Protoss_Gateway) < 2)
		{
			bot.spaceManager.build(UnitType.Protoss_Gateway);
		}
		
		if (UnitTracker.count(UnitType.Protoss_Photon_Cannon) >= Math.min(4, cannonCount)
				&& (UnitTracker.count(UnitType.Protoss_Nexus) >= 2 || !fastExpand)
				&& (UnitTracker.count(UnitType.Protoss_Gateway) < 3 || fastExpand || UnitTracker.count(UnitType.Protoss_Observatory) > 0)
				&& bot.getAvailableMinerals() >= 250
				&& UnitTracker.count(UnitType.Protoss_Gateway) < 5)
		{
			bot.spaceManager.build(UnitType.Protoss_Gateway);
		}
		
		if (UnitTracker.count(UnitType.Protoss_Nexus) >= 2
				&& bot.getAvailableMinerals() >= 500
				&& UnitTracker.count(UnitType.Protoss_Gateway) < 7)
		{
			bot.spaceManager.build(UnitType.Protoss_Gateway);
		}
		
		if(UnitTracker.count(UnitType.Protoss_Assimilator) < 2
				&& bot.getAvailableMinerals() >= 100 
				&& UnitTracker.getGeyserCount() > 0
				&& UnitTracker.count(UnitType.Protoss_Gateway) > 0
				&& (count(ZEALOT) >= 2 || game.enemy().getRace() != Race.Protoss || dragoonOnly)
				&& (count(ASSIMILATOR) == 0 || count(CYBERNETICS_CORE) > 0))
		{
			bot.spaceManager.build(UnitType.Protoss_Assimilator);
		}
		
		if (bot.getAvailableMinerals()>= 200 
				&& UnitTracker.count(UnitType.Protoss_Cybernetics_Core) < 1
				&& self.completedUnitCount(UnitType.Protoss_Gateway) > 0
				&& (count(ZEALOT) >= 2 || game.enemy().getRace() != Race.Protoss || dragoonOnly))
		{
			bot.spaceManager.build(UnitType.Protoss_Cybernetics_Core);
		}
		
		if (bot.getAvailableGas() >= 200 && bot.getAvailableMinerals() >= 200
				&& UnitTracker.count(UnitType.Protoss_Cybernetics_Core) > 0
				&& UnitTracker.count(UnitType.Protoss_Gateway) >= 3
				&& UnitTracker.count(UnitType.Protoss_Robotics_Facility) == 0)
		{
			bot.spaceManager.build(UnitType.Protoss_Robotics_Facility);
		}
		
		if (bot.getAvailableGas() >= 200 && bot.getAvailableMinerals() >= 200
				&& UnitTracker.count(UnitType.Protoss_Cybernetics_Core) > 0
				&& UnitTracker.count(UnitType.Protoss_Gateway) >= 3
				&& UnitTracker.count(UnitType.Protoss_Robotics_Facility) < 2
				&& count(ROBO_SUPPORT) > 0
				&& reavers)
		{
			bot.spaceManager.build(UnitType.Protoss_Robotics_Facility);
		}
		
		if (bot.getAvailableGas() >= 50 && bot.getAvailableMinerals() >= 100
				&& self.completedUnitCount(UnitType.Protoss_Robotics_Facility) > 0
				&& UnitTracker.count(UnitType.Protoss_Observatory) == 0)
		{
			bot.spaceManager.build(UnitType.Protoss_Observatory);
		}
		
		if (completed(ROBOTICS_FACILITY) > 0
				&& reavers
				&& count(ROBO_SUPPORT) == 0
				&& minerals() >= 150
				&& gas() >= 100)
		{
			bot.spaceManager.build(ROBO_SUPPORT);
		}
	}
	
	@Override
	public boolean overrideStructureOrder(Game game, Player self, Tyr bot, Agent agent)
	{
		if (agent.unit.getType() == UnitType.Protoss_Gateway && !agent.unit.isTraining())
		{
			if (detectionNeeded && UnitTracker.count(UnitType.Protoss_Observer) == 0 
					&& (bot.getAvailableMinerals() <= 325 || bot.getAvailableGas() <= 150))
					return true;
			if (reavers && UnitTracker.count(ROBOTICS_FACILITY) == 0 
					&& count(DRAGOON) >= 5
					&& (bot.getAvailableMinerals() <= 325 || bot.getAvailableGas() <= 250))
					return true;
			if (reavers
					&& completed(ROBOTICS_FACILITY) == 1
					&& completed(ROBO_SUPPORT) == 1
					&& count(REAVER) == 0
					&& count(DRAGOON) >= 5
					&& (bot.getAvailableMinerals() <= 325 || bot.getAvailableGas() <= 250))
					return true;
			if (reavers && completed(ROBOTICS_FACILITY) == 1
					&& count(ROBO_SUPPORT) == 0
					&& count(DRAGOON) >= 5
					&& (bot.getAvailableMinerals() <= 325 || bot.getAvailableGas() <= 250))
					return true;
			if ((UnitTracker.count(UnitType.Protoss_Zealot) <= UnitTracker.count(UnitType.Protoss_Dragoon) || self.completedUnitCount(UnitType.Protoss_Cybernetics_Core) == 0
					&& (!limitZealots || count(ZEALOT) < 5))
					&& !dragoonOnly
					&& bot.getAvailableMinerals() >= 100)
				agent.unit.build(UnitType.Protoss_Zealot);
			else if ((UnitTracker.count(UnitType.Protoss_Zealot) > UnitTracker.count(UnitType.Protoss_Dragoon) || dragoonOnly)
					&& bot.getAvailableMinerals() >= 125 && bot.getAvailableGas() >= 50)
				agent.unit.build(UnitType.Protoss_Dragoon);
			return true;
		}
		else if (agent.unit.getType() == UnitType.Protoss_Forge && !agent.unit.isUpgrading())
		{
			if(bot.getAvailableMinerals() >= UpgradeType.Protoss_Ground_Weapons.mineralPrice()
					&& bot.getAvailableGas() >= UpgradeType.Protoss_Ground_Weapons.gasPrice())
				agent.unit.upgrade(UpgradeType.Protoss_Ground_Weapons);
			
			if(bot.getAvailableMinerals() >= UpgradeType.Protoss_Ground_Armor.mineralPrice()
					&& bot.getAvailableGas() >= UpgradeType.Protoss_Ground_Armor.gasPrice())
				agent.unit.upgrade(UpgradeType.Protoss_Ground_Armor);
		}
		else if (agent.unit.getType() == UnitType.Protoss_Cybernetics_Core && !agent.unit.isUpgrading())
		{
			if(bot.getAvailableMinerals() >= UpgradeType.Singularity_Charge.mineralPrice()
					&& bot.getAvailableGas() >= UpgradeType.Singularity_Charge.gasPrice())
				agent.unit.upgrade(UpgradeType.Singularity_Charge);
		}
		else if (agent.unit.getType() == UnitType.Protoss_Robotics_Facility)
		{
			if ((UnitTracker.count(UnitType.Protoss_Observer) <= 2)
					&& bot.getAvailableMinerals() >= 25
					&& bot.getAvailableGas() >= 75
					&& !agent.unit.isTraining())
				agent.unit.build(UnitType.Protoss_Observer);
			else if (completed(ROBO_SUPPORT) > 0
					&& gas() >= 100
					&& minerals() >= 200
					&& !agent.unit.isTraining())
			{
				agent.unit.train(REAVER);
			}
		}
		return false;
	}

	public CannonWall dragoonOnly()
	{
		this.dragoonOnly = true;
		return this;
	}

	public CannonWall goReavers()
	{
		this.reavers = true;
		return this;
	}

	public CannonWall doNotExpand()
	{
		this.doNotExpand = true;
		return this;
	}
}
