/*
* 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 com.tyr.DebugMessages;
import com.tyr.EnemyManager;
import com.tyr.EnemyPosition;
import com.tyr.Tyr;
import com.tyr.agents.Agent;
import com.tyr.unitgroups.HarassBaseGroup;
import com.tyr.unitgroups.MineralWorkers;

import bwapi.Color;
import bwapi.Game;
import bwapi.Order;
import bwapi.Player;
import bwapi.Position;
import bwta.BaseLocation;

/**
 * This class implements a solution for harassing the opponents expands with vultures.
 */
public class DropHarassSolution extends Solution 
{
	/**
	 * The unit group of units that perform the harass.
	 */
	private HarassBaseGroup harassGroup;
	
	/**
	 * The position of the base we are currently attacking in the list of bases returned by EnemyManager.getOrderedexpands().
	 */
	private int currentPos;
	
	/**
	 * The direction in which we are currently going through the list of bases returned by EnemyManager.getOrderedexpands().
	 */
	private int currentDir = 1;
	
	/**
	 * The position of the base we currently intend to harass.
	 */
	private Position target;
	
	/**
	 * The list of dropships we will use for the harass.
	 */
	private ArrayList<Agent> dropships;
	
	/**
	 * The list of units which will perform the drop.
	 */
	private ArrayList<Agent> units;
	
	/**
	 * List of all expands, in the order that they are encountered in a sweep around the map.
	 * Includes opponents main.
	 */
	private ArrayList<Position> orderedExpands;
	
	/**
	 * The mode our drop is in.
	 * Either load, moveOut or attack.
	 */
	private int mode = load;
	
	private static final int load = 0;
	private static final int moveOut = 1;
	private static final int attack = 2;
	
	/**
	 * This class implements a solution for harassing the opponents expands with vultures.
	 * @param task The task that started this solution.
	 * @param dropships The list of dropships we will use for the harass.
	 * @param units The list of units which will perform the drop. 
	 */
	public DropHarassSolution(Task task, ArrayList<Agent> dropships, ArrayList<Agent> units) 
	{
		super(task);
		determineTarget();
		this.dropships = dropships;
		this.units = units;
	}
	
	@Override
	public void onFrame(Game game, Player self, Tyr bot)
	{
		// Cleanup the lists of units.
		for (int i = dropships.size()-1; i>= 0; i--)
			if(dropships.get(i).isDead())
				dropships.remove(i);
		for (int i = units.size()-1; i>= 0; i--)
			if(units.get(i).isDead())
				units.remove(i);
		
		if (units.size() == 0)
			mode = load;
		
		DebugMessages.addMessage("Dropship mode = " + mode);
		
		if (mode == load)
			load();
		else if (mode == moveOut)
			moveOut();
		else if (mode == attack)
			attack();
	}
	
	/**
	 * attack mode, where the actual attack takes place.
	 */
	private void attack() 
	{
		if (dropships.size() == 0)
		{
			// Manage the harass group.
			harassGroup.cleanup();
			harassGroup.onFrame(Tyr.game, Tyr.self, Tyr.bot);
			
			return;
		}
		
		Agent dropship = dropships.get(0);
		boolean isCarrying = false;
		for(Agent agent : units)
			if(agent.unit.isLoaded())
			{
				dropships.get(0).unit.unload(agent.unit);
				isCarrying = true;
				break;
			}
		if (isCarrying && Tyr.bot.spaceManager.map[dropship.unit.getTilePosition().getX()][dropship.unit.getTilePosition().getY()] != 1)
			dropship.unit.move(target);
		if(isCarrying && Tyr.bot.spaceManager.map[dropship.unit.getTilePosition().getX()][dropship.unit.getTilePosition().getY()] == 1)
		{
			if(dropship.unit.getOrder() == Order.Move)
				dropship.unit.stop();
		}
		
		if (!isCarrying)
		{
			dropship.unit.move(Tyr.tileToPosition(Tyr.self.getStartLocation()));

			// Manage the harass group.
			harassGroup.cleanup();
			harassGroup.onFrame(Tyr.game, Tyr.self, Tyr.bot);
		}
	}
	
	/**
	 * moveOut mode. The dropship moves out to an enemy base.
	 */
	private void moveOut() 
	{
		// See if we need to change the target.
		determineTarget();
		int dist = 0;
		for(Agent agent : dropships)
		{
			agent.unit.move(target);
			Tyr.game.drawLineMap(agent.unit.getX(), agent.unit.getY(), target.getX(), target.getY(), Color.Blue);
			dist = Math.max(dist, agent.distanceSquared(target));
		}
		
		if (dist > 200*200)
			return;
		
		// See if we have found an enemy base.
		for (EnemyPosition enemy : EnemyManager.getManager().enemyBuildingMemory)
		{
			if (!enemy.type.isResourceDepot())
				continue;
			if (enemy.pos.getDistance(target) < 100)
			{
				mode = attack;
				harassGroup = new HarassBaseGroup(target, false);
				currentDir *= -1;
				for (Agent agent : units)
					harassGroup.add(agent);
				break;
			}
		}
	}

	/**
	 * Load mode, loads the units into the dropship.
	 */
	private void load()
	{
		boolean done = true;
		for (Agent agent : units)
		{
			if (!agent.unit.isLoaded())
			{
				done = false;
				dropships.get(0).unit.load(agent.unit);
				if (agent.unit.getTargetPosition() == null || agent.unit.getTargetPosition().getDistance(dropships.get(0).unit.getPosition()) >= 100)
					agent.unit.move(dropships.get(0).unit.getPosition());
			}
		}
		if (done)
		{
			mode = moveOut;
			return;
		}
	}
	
	/**
	 * Determines the base we want to attack.
	 * @return Whether the method call actually changes the target.
	 */
	private boolean determineTarget()
	{
		boolean result = false;
		
		ArrayList<Position> orderedExpands = EnemyManager.getManager().getOrderedExpands();
		
		if (orderedExpands != null)
		{
			for(int i=0; i<orderedExpands.size(); i++)
			{
				Position pos = orderedExpands.get(i);
				Tyr.drawCircle(pos, Color.Red, 32);
				Tyr.game.drawTextMap(pos.getX(), pos.getY(), i + "");
			}
			
			if (target != null)
				Tyr.drawCircle(target, Color.Red);
		}
		// If the target has not previously been initialized, initalize it.
		if (target == null)
		{
			if (orderedExpands == null)
			{
				DebugMessages.addMessage("orderedExpands is null.");
				return false;
			}
			
			currentPos = EnemyManager.getManager().getSelfPos();
			if(currentPos != -1)
			{
				target = orderedExpands.get(currentPos);
				result = true;
			}
		}
		
		// Determine whether we are done harassing the current target.
		for(int i=0; i < 2*orderedExpands.size(); i++)
		{
			boolean isIsland = false;
			for (BaseLocation loc : Tyr.bot.expands)
			{
				if (!loc.isIsland())
					continue;
				if (loc.getDistance(target) <= 128)
					isIsland = true;
			}
			
			// If the target is invisible, we are not done.
			if (!isIsland && target != null && !Tyr.game.isVisible(Tyr.positionToTile(target)))
				break;
			
			// If the vultures are too far away from that base, we do not yet look for a new target.
			boolean closeEnough = false;
			
			// If we have a base there, we do not need to harass it.
			for (MineralWorkers base : Tyr.bot.workForce.mineralWorkers)
				if (base.resourceDepot != null && base.resourceDepot.getDistance(target) < 100)
					closeEnough = true;
			
			if (!isIsland && !closeEnough && dropships != null)
			{
				for(Agent agent : dropships)
				{
					if (agent == null)
						continue;
					
					if (agent.distanceSquared(target) < 128 * 128)
						closeEnough = true;
				}
			}
			if (!isIsland && !closeEnough)
				break;
			
			// We are done with the current target, get the next one.
			nextTarget();
			
			result = true;
		}
		
		return result;
	}
	
	/**
	 * Gets us the next target to harass.
	 */
	@SuppressWarnings("unchecked")
	private void nextTarget()
	{
		if (orderedExpands == null)
		{
			orderedExpands = (ArrayList<Position>)EnemyManager.getManager().getOrderedExpands().clone();
			if (orderedExpands == null)
				return;
			if (Tyr.bot.suspectedEnemy.size() == 1)
				orderedExpands.add(Tyr.bot.suspectedEnemy.get(0).getPosition());
		}
		
		currentPos += currentDir;
		
		// If we are at the end of the list of expands, we go back.
		if (currentPos >= orderedExpands.size() || currentPos < 0)
		{
			currentDir *= -1;
			currentPos += 2*currentDir;
		}
		
		target = orderedExpands.get(currentPos);
	}

	/**
	 * Whether the harass is done.
	 * @return Whether the harass is done.
	 */
	public boolean done() 
	{
		return units.size() == 0 || (mode != attack && dropships.size() == 0);
	}

	/**
	 * Clears the solution once it is done.
	 */
	public void clear() 
	{
		for (Agent dropship : dropships)
			Tyr.bot.hobos.add(dropship);
		for (Agent agent : units)
			Tyr.bot.hobos.add(agent);
	}
	
}
