/* 
 * Tactic is the legal property of its developers, whose names are too numerous 
 * to list here.  Please refer to the COPYRIGHT file distributed with this 
 * source distribution. 
 * 
 * This library is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU Lesser General Public 
 * License as published by the Free Software Foundation; either 
 * version 2.1 of the License, or (at your option) any later version. 
 * 
 * This library 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 
 * Lesser General Public License for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public 
 * License along with this library; if not, write to the Free Software 
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA 
 *
 * See README for more informations
 *
 * OrderAttack.cpp
 *
 * ...
 * Date 22/03/06
 *
 */
#include "OrderRegroup.h"
#include "GroupAI.h"
#include <math.h>

OrderRegroup::OrderRegroup() {}

OrderRegroup::OrderRegroup(GroupAI* g) : Order(g)
{
	regrouped = false;
}

void OrderRegroup::execute()
{
	DebugAI::trace('o', "Executing OrderRegroup");
	Point2D target;

	Order::execute();
	regrouped = false;
	myGroup->resetActions();

	target = myGroup->getPosition();
	int width = ceil(sqrt((float)myGroup->getNumber()));
	int y = 0;
	float space = 0.5f;
	for (std::vector<Unit*>::iterator it = myGroup->getUnits()->begin(); it != myGroup->getUnits()->end();)
	{
		for(int x = 0; x < width && it != myGroup->getUnits()->end(); x++, ++it){
			(*it)->notifyEndOrder("OrderRegroup");
			Point2D p(x*space,y*space);
			(*it)->goTo(target + p);
		}
		y++;
	}

	DebugAI::trace('o', "OrderRegroup Executed");
}

OrderRegroup::~OrderRegroup() {}

FuzzyValueName OrderRegroup::getType()
{
	return ORDER_REGROUP;
}

void OrderRegroup::notifyEndOrder(Unit* u)
{
	Order::notifyEndOrder(u);

	if (isFinished()) {
		regrouped = true;
		myGroup->setObey(false);
		myGroup->update();
	}
}

bool OrderRegroup::isRegrouped()
{
	return regrouped;
}

