/*
* 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.Tyr;
import com.tyr.agents.Agent;
import com.tyr.agents.None;
import com.tyr.requirements.Requirement;
import bwapi.Game;
import bwapi.Player;
import bwapi.Position;
import bwapi.UnitType;


/**
 * A task that manages building buildings at a certain location.
 */
public class BuildAtLocationTask extends Task
{
	/**
	 * The target position where we want to build the buildings.
	 */
	private Position target;
	
	/**
	 * The types of buildings that we will build.
	 */
	private List<UnitType> types = new ArrayList<UnitType>();
	
	/**
	 * Requirements for the units that we will build.
	 */
	private List<Requirement> requirements = new ArrayList<Requirement>();
	
	private boolean keepExpandsFree;
	
	public static boolean stop;
	
	/**
	 * A task that determines whether we are ready to attack the opponent.
	 */
	public BuildAtLocationTask(Position target, boolean keepExpandsFree)
	{
		this.target = target;
		this.keepExpandsFree = keepExpandsFree;
	}
	
	@Override
	public boolean isRequired(Game game, Player self, Tyr bot) 
	{
		return true;
	}
	
	@Override
	public void solve(Game game, Player self, Tyr bot)
	{
		if (stop)
		{
			((BuildAtLocationSolution)solution).clear();
			return;
		}
		// See if the solution needs a worker.
		if (((BuildAtLocationSolution)solution).needBuilder())
		{
			final Agent builder = bot.workForce.pop(target);
			if (builder != null)
			{
				builder.order(new None(builder));
				builder.unit.stop();
				((BuildAtLocationSolution)solution).setBuilder(builder);
			}
		}
		
		// We call the super class, which will manage the actual constructing of the buildings.
		super.solve(game, self, bot);
	}

	@Override
	public void findSolution(Game game, Player self, Tyr bot)
	{
		solution = new BuildAtLocationSolution(this, target, types, requirements, keepExpandsFree);
	}
	
	public void addBuilding(UnitType buildingType, Requirement requirements)
	{
		types.add(buildingType);
		this.requirements.add(requirements);
		if (solution != null)
			((BuildAtLocationSolution)solution).addBuilding(buildingType, requirements);
	}
}
