#include "UnitRatio.h"
#include "Overseer.h"

UnitRatio::UnitRatio( UnitType a, UnitType b, float firstTarget, float secondTarget, Overseer* o, int hardLimitSecond)
{
	first = a;
	second = b;
	fTarget = firstTarget;
	sTarget = secondTarget;
	overseer = o;
	limitSecond = hardLimitSecond;
}


UnitType UnitRatio::getReccomendedUnit()
{
	if(first == UnitTypes::None) {
		int numSecond = 0;
		if(second.isBuilding()) {
			numSecond = (overseer->getUnitManager()->countFriendlyBuildings(second));
		} else {
			numSecond = (overseer->getUnitManager()->countFriendlyUnits(second));
		}
		
		if(numSecond < sTarget) {
			return second;
		}
		return UnitTypes::None;
	}
	// first: count how many instances of types a and b we have
	float numFirst = (float)(overseer->getUnitManager()->countFriendlyUnits(first));
	float numSecond = (float)(overseer->getUnitManager()->countFriendlyUnits(second));

	if(limitSecond != 0 && numSecond >= limitSecond) {
		return UnitTypes::None;
	}

	numFirst = numFirst + overseer->getArbitrator()->countProjectedUnitsOfType(first, 30);
	numSecond = numSecond + overseer->getArbitrator()->countProjectedUnitsOfType(second, 30);

	if((numFirst/numSecond) == (fTarget/sTarget) && second.isBuilding()) {
		return UnitTypes::None;
	}

	////////Broodwar->sendText("I have... %f of %s", numFirst, first.getName().c_str());
	////////Broodwar->sendText("so therefore, I should have... %f of %s", ((numFirst/fTarget)*sTarget), second.getName().c_str());

	if(numSecond <= ((numFirst/fTarget)*sTarget)) {

		if(second == UnitTypes::Protoss_Gateway && numSecond >= (numFirst*numSecond)) {

		} else {
		return second; // zealots
		}
	}

	// can't figure out how to fix this bug in an elegant way
	// so lets just hack it
	if(first == UnitTypes::Protoss_Nexus) {
		return UnitTypes::None;
	} else {
		return first;
	}
}

// the further away from 0 a magnitude is, the more out of sync it is with what we desire
float UnitRatio::getMagnitude()
{
	if(first == UnitTypes::None) {
		return 1.0;
	}

	float numFirst = (float)(overseer->getUnitManager()->countFriendlyUnits(first));
	float numSecond = (float)(overseer->getUnitManager()->countFriendlyUnits(second));

	// massive hack
	if(second == UnitTypes::Protoss_Gateway) {
		if(numSecond >= 6) {
			return 1.0;
		}
	}
	numFirst = numFirst + (float)(overseer->getArbitrator()->countProjectedUnitsOfType(first, 5));
	numSecond = numSecond + (float)(overseer->getArbitrator()->countProjectedUnitsOfType(second, 5));

	float existingRatio = numFirst/numSecond;
	float targetRatio = fTarget/sTarget;
	return fabs(existingRatio-targetRatio);
}

std::pair<UnitType, UnitType> UnitRatio::getSubjects()
{
	return std::make_pair(first, second);
}

void UnitRatio::setID(int num)
{
	id = num;
}

int UnitRatio::getID()
{
	return id;
}
