package com.tyr.builds;

import bwapi.Game;
import bwapi.Player;
import bwapi.Race;
import bwapi.Unit;

import com.tyr.EnemyManager;
import com.tyr.Settings;
import com.tyr.Tyr;
import com.tyr.UnitTracker;
import com.tyr.agents.Agent;
import com.tyr.unitgroups.AttackGroup;

public class GatewayPush extends CompositeBuildOrder
{
	private Race opponentRace = Race.Unknown;
	private BuildOrder buildOrder;
	
	
	@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);
		this.add(new WorkerScoutPart(100));
		AttackGroup.hunting = true;
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot)
	{
		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 (buildOrder == null && opponentRace != Race.Unknown)
		{
			if (opponentRace == Race.Protoss)
				buildOrder = new DragoonPush(25, false, true, false, false, true, false, false);
			else if (opponentRace == Race.Terran)
				buildOrder = new DragoonPush(30, 15, false, false, false, false, false, false, true);
			else if (opponentRace == Race.Zerg)
				buildOrder = new DragoonPush(25, false, true, true, false, true, false, false);
			buildOrder.initialize(game, self, bot);
		}
		
		if (buildOrder != null)
		{
			buildOrder.onFrame(game, self, bot);
			return;
		}
		
		super.onFrame(game, self, bot);
		
		//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) < 1
				&& completed(PYLON) > 0)
		{
			bot.spaceManager.build(GATEWAY);
		}
	}
	
	@Override
	public boolean overrideStructureOrder(Game game, Player self, Tyr bot, Agent agent)
	{
		if (buildOrder != null)
			return buildOrder.overrideStructureOrder(game, self, bot, agent);
		
		return super.overrideStructureOrder(game, self, bot, agent);
	}
}
