#include "Squad.h"

Squad::Squad()
{
	this->action = "";
	this->center = TilePosition(0, 0);
}

void Squad::addUnit(CUnit unit)
{
	this->units.push_back(unit);
	this->airDamage += unit.unitType.airWeapon().damageAmount();
	this->groundDamage += unit.unitType.groundWeapon().damageAmount();
}

void Squad::attack(std::pair<TilePosition, int> baseToAttack)
{
	this->action = "attack";
	Position attackLocation = Position(baseToAttack.first);
	this->target = TilePosition(attackLocation);
	for (auto u : this->units)
	{
		u.unit->attack(attackLocation);
		if (u.unit->getType() == UnitTypes::Zerg_Overlord)
		{
			u.unit->move(this->units.at(rand() % this->units.size()).unit->getPosition());
		}
	}
}

bool Squad::contains(CUnit unit)
{
	for (size_t i = 0; i < this->units.size(); i++)
	{
		if (this->units.at(i).unit->getID() == unit.unit->getID()) return true;
	}
	
	return false;
}

bool Squad::containsType(UnitType ut)
{
	for (size_t i = 0; i < this->units.size(); i++)
	{
		if (this->units.at(i).unit->getType() == ut) return true;
	}

	return false;
}

void Squad::freeDrones()
{
	for (auto u : this->units)
	{
		if (u.unit->getType() == UnitTypes::Zerg_Drone)
		{
			Macro::freeUnit(Util::getUnitIndex(u.unit));
		}
	}
}

void Squad::updateCenter()
{
	int averageX = 0;
	int averageY = 0;
	int size = this->units.size();
	if (size == 0) size = 1;

	for (auto u : this->units)
	{
		averageX += u.unit->getTilePosition().x;
		averageY += u.unit->getTilePosition().y;
	}

	this->center = TilePosition((averageX / size), (averageY / size));
}

void Squad::updateDamage()
{
	int ground = 0;
	int air = 0;
	for (auto u : this->units)
	{
		ground += u.unitType.groundWeapon().damageAmount();
		air += u.unitType.airWeapon().damageAmount();
	}
	this->groundDamage = ground;
	this->airDamage = air;
}
