/*
* 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.tasks;

import java.util.ArrayList;
import java.util.List;

import com.tyr.Force;
import com.tyr.ForceTracker;
import com.tyr.Tyr;
import com.tyr.agents.Agent;
import com.tyr.agents.None;
import com.tyr.agents.VesselSupport;

import bwapi.Color;
import bwapi.Game;
import bwapi.Player;


public class ScienceHurtsSolution extends Solution 
{
	private ArrayList<Agent> scienceVessels = new ArrayList<Agent>();
	
	/**
	 * A single vessel used explicitly to defend the main base.
	 */
	Agent defendingVessel = null;
	
	public ScienceHurtsSolution(Task task)
	{
		super(task);
	}

	@Override
	public void onFrame(Game game, Player self, Tyr bot)
	{
		if (defendingVessel != null && defendingVessel.isDead())
			defendingVessel = null;
		
		for (int i=scienceVessels.size()-1; i >= 0; i--)
			if(scienceVessels.get(i).isDead())
				scienceVessels.remove(i);
		
		List<Force> forces = ForceTracker.forces;
		for (Agent vessel : scienceVessels)
		{
			if (vessel.getCommand() != null 
					&& vessel.getCommand() instanceof VesselSupport 
					&& ((VesselSupport)vessel.getCommand()).supportedForce != null)
			{
				vessel.drawCircle(Color.Purple, 16);
				continue;
			}
			
			if (vessel == defendingVessel)
				continue;
			
			if (defendingVessel == null && scienceVessels.size() > 1)
			{
				defendingVessel = vessel;
				continue;
			}
			
			// Find a force to assign the science vessel to.
			Force closest = null;
			int distSq = Integer.MAX_VALUE;
			int fs = 0;
			for (Force f : forces)
			{
				if (f.done() || f.disabled())
					continue;
				int newDistSq = vessel.distanceSquared(f.getCenter());
				if (newDistSq < distSq)
				{
					newDistSq = distSq;
					closest = f;
				}
				fs++;
			}

			if (fs == 0)
				vessel.drawCircle(Color.Yellow, 16);
			else if (closest == null)
				vessel.drawCircle(Color.Green, 16);
			else
				vessel.drawCircle(Color.Blue, 16);
			
			vessel.order(new VesselSupport(vessel, closest));
		}
	}

	public void add(Agent agent) 
	{
		agent.order(new None(agent));
		scienceVessels.add(agent);
	}

}
