#include "PhotonCannonMicroBehaviour.h"


PhotonCannonMicroBehaviour::PhotonCannonMicroBehaviour( UnitModel* sub , UnitManager* u )
{
	subject = sub;
	unitManager = u;
	attacking = false;
	moving = false;
	targettingSystem = new TargetEvaluator(sub);
	currentTarget = NULL;
	currentTargetValue = -1000;
	id = PROTOSS_PHOTON_CANNON;
}

bool PhotonCannonMicroBehaviour::execute()
{
	//Broodwar->drawEllipseMap(subject->getPosition().x(), subject->getPosition().y(), 16, 16, Colors::Orange, false);
	std::vector<UnitModel*> units = unitManager->getAllEnemyUnitsInRange(subject->getPosition(), UnitTypes::Protoss_Photon_Cannon.sightRange()*1.2);
	if(units.empty()) {
		return false;
	}
	int bestScoreSoFar = 0;
	UnitModel* bestTarget = NULL;

		for (vector<UnitModel*>::iterator i = units.begin(); i != units.end(); ++i)
		{
			UnitModel* cur = *i;
			if(!cur->getUnit()->isVisible() || subject->getPosition().getDistance(cur->getPosition()) > subject->getType().groundWeapon().maxRange()) { 
				continue;
			}
			

			if(bestTarget == NULL) {
				bestTarget = cur;
			} else {
				int targettingPenalty = 0;
				targettingPenalty = unitManager->calculateTargettingPenalty(cur->getUnit(), subject);
				int candidateValue = targettingSystem->calculateValueOf(cur, targettingPenalty);
				if(candidateValue > bestScoreSoFar) {
						bestScoreSoFar = candidateValue;
						bestTarget = cur;
				}
			}
		}
		if(bestTarget == NULL) {
			return true;
		}
		if(subject->getUnit()->getGroundWeaponCooldown() == 0) {
			//if(bestTarget != NULL && !subject->getUnit()->isAttacking() && !subject->getUnit()->isStartingAttack() && !subject->getUnit()->isAttackFrame()) {
				subject->getUnit()->attack(bestTarget->getUnit());
				unitManager->declareTargetToMap(subject, bestTarget->getUnit());
			//}
		}
		return true;
}

void PhotonCannonMicroBehaviour::nudge()
{

}
