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

import com.tyr.Tyr;
import com.tyr.agents.Agent;

import bwapi.Game;
import bwapi.Player;
import bwapi.Unit;
import bwapi.WeaponType;


/**
 * A task that destroys a given list of units.
 */
public class DestroyBuildingsTask extends Task
{
	private List<Unit> targets;
	
	/**
	 * A task that constantly pushes the opponent.
	 */
	public DestroyBuildingsTask(List<Unit> targets)
	{
		this.targets = targets;
	}
	
	@Override
	public boolean isRequired(Game game, Player self, Tyr bot) 
	{
		return targets != null && targets.size() > 0;
	}
	
	@Override
	public void solve(Game game, Player self, Tyr bot)
	{
		if (targets == null)
			return;
		for (int i=targets.size()-1; i >= 0; i--)
			if (targets.get(i) == null || targets.get(i).getRemoveTimer() > 0 || targets.get(i).getHitPoints() <= 0 || !targets.get(i).exists())
				targets.remove(i);
		
		if (targets.size() == 0)
			((DestroyBuildingsSolution)solution).done(bot.hobos);
		else
		{
			for (int i = bot.homeGroup.units.size()-1; i>=0; i--)
			{
				Agent agent = bot.homeGroup.units.get(i);
				if (agent.unit.getType().groundWeapon() != WeaponType.None)
				{
					((DestroyBuildingsSolution)solution).add(agent);
					bot.homeGroup.units.remove(i);
				}
			}
		}
		if (!targets.isEmpty())
			((DestroyBuildingsSolution)solution).setTarget(targets.get(targets.size()-1));
		
		// We call the super class, which will send the units out to attack.
		super.solve(game, self, bot);
	}

	@Override
	public void findSolution(Game game, Player self, Tyr bot)
	{
		solution = new DestroyBuildingsSolution(this);
	}
}
