#include "SCVBehaviour.h"
#include "SquadAgent.h"
#include "CombatAgent.h"

using namespace BWAPI;

SCVBehaviour::SCVBehaviour(Unit* unit, class SquadAgent* squad)
	: _unit(unit),
	_squad(squad),
	_logger(log4cxx::Logger::getLogger("SquadManager.CombatAgent.SCV")),
	_lastPosition(Positions::None)
{

}

void SCVBehaviour::byDefault()
{
	LOG4CXX_TRACE(_logger,"SCV micro START");
	if (_unit->isIdle() && !_unit->isRepairing()) {
		Unit* tank = NULL;
		Unit* vulture = NULL;
		Unit* mecha = NULL;

		for(CombatUnitSet::const_iterator i=_squad->_squadUnits.begin();i!=_squad->_squadUnits.end();++i) {
			if ((*i)->_unit!=NULL && (*i)->_unit->getHitPoints()!=(*i)->_unit->getType().maxHitPoints()) {
				if ((*i)->_unit->getType()==UnitTypes::Terran_Siege_Tank_Siege_Mode || (*i)->_unit->getType()==UnitTypes::Terran_Siege_Tank_Tank_Mode)
					tank = (*i)->_unit;
				else if (_squad->_state == SquadAgent::GetPosition) {
					if ((*i)->_unit->getType() == UnitTypes::Terran_Vulture)
						vulture = (*i)->_unit;
					else if ((*i)->_unit->getType().isMechanical() && (*i)->_unit != _unit)
						mecha = (*i)->_unit;
				}
			}
		}

		if (tank != NULL) _unit->repair(tank);
		else if (vulture != NULL) _unit->repair(vulture);
		else if (mecha != NULL) _unit->repair(mecha);
	} else { // We are reparing
// 		if (squad->_state == SquadAgent::Fight && _unit->getTarget()->getType() == UnitTypes::Terran_Vulture) {
// 			_unit->stop(); // cancel reparigin order
// 		}
	}
	LOG4CXX_TRACE(_logger,"SCV micro END");
}

void SCVBehaviour::onGetPosition(Position targetPosition)
{
    LOG4CXX_TRACE(_logger,"SCV get position START");
	if (_unit->getOrder() == Orders::PlayerGuard) {
		// Follow closest tank
		CombatAgent* tank = _squad->getClosestUnitTo(_unit->getPosition(), UnitTypes::Terran_Siege_Tank_Tank_Mode);
		if (tank == 0) tank = _squad->getClosestUnitTo(_unit->getPosition(), UnitTypes::Terran_Siege_Tank_Siege_Mode);
		if (tank == 0) tank = _squad->getClosestUnitTo(_unit->getPosition(), UnitTypes::None);
        if (tank == 0) {
            LOG4CXX_TRACE(_logger,"SCV moving to position");
            _unit->move(targetPosition);
        } else {
            LOG4CXX_TRACE(_logger,"SCV following");
            _unit->follow(tank->_unit);
        }
	}
    LOG4CXX_TRACE(_logger,"SCV get position END");
}

void SCVBehaviour::onGetNewPosition(Position targetPosition)
{
    _unit->move(targetPosition);
}


void SCVBehaviour::onCombat(BWAPI::Unit *bestTarget, const UnitSet &enemies)
{

}

void SCVBehaviour::onStop() {};
void SCVBehaviour::onHold() {};