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

import java.util.ArrayList;

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

import bwapi.Game;
import bwapi.Player;


/**
 * This class is used as the basis for most BuildOrders.
 * Subclasses can add BuildOrder objects to the parts list.
 * Each of these build order parts will be executed once per frame.
 */
public abstract class CompositeBuildOrder extends BuildOrder
{
	/**
	 * The separate parts of the composite buildorder
	 */
	private ArrayList<BuildOrder> parts = new ArrayList<BuildOrder>();
	
	/**
	 * Is true when the parts have been initialized.
	 */
	boolean initialized = false;

	/**
	 * Performs initalization of the various parts of the bot.
	 */
	@Override
	public void initialize(Game game, Player self, Tyr bot)
	{
		for(BuildOrder part : parts)
			part.initialize(game, self, bot);
		
		initialized = true;
	}
	
	/**
	 * Each of the on frame methods for the parts is executed.
	 */
	@Override
	public void onFrame(Game game, Player self, Tyr bot)
	{
		for(BuildOrder part : parts)
			part.onFrame(game, self, bot);
	}

	/**
	 * The parts may also make use of the overrideStructureOrder method.
	 * This allows them to override the standard orders that are given to production structures.
	 * As soon as one of the parts decides to override the order, this is considered final.
	 * None of the other parts will get a chance to override the order.
	 */
	@Override 
	public boolean overrideStructureOrder(Game game, Player self, Tyr bot, Agent agent)
	{
		for(BuildOrder part : parts)
			if (part.overrideStructureOrder(game, self, bot, agent))
				return true;
		
		return false;
	}
	
	/**
	 * Adds a BuildOrder part to the list of parts.
	 * @param part The BuildOrder part that will be added.
	 */
	public void add(BuildOrder part)
	{
		parts.add(part);
		
		// If the other parts have already been initialized, this part should be initialized as well.
		if(initialized)
			part.initialize(Tyr.game, Tyr.game.self(), Tyr.bot);
	}
}
