#include "stdafx.h"
#include "GroupCarefulAttackBehavior.h"
#include "../../../../../../PerceptualState/PerceptualState.h"
#include <BWAPI.h>

///////////////////////////////////////////////////
// Engaging state
///////////////////////////////////////////////////

GroupCarefulAttackBehavior::Engaging::Engaging(GroupCarefulAttackBehavior& behavior)
  : BehaviorStateT(behavior)
  , m_enemyUnitDestroyedEventHandler(*this)
  , m_events(/*m_enemyUnitInLocationEvent*/)
  , m_transitions()
{
}

void GroupCarefulAttackBehavior::Engaging::onEnter()
{
  m_context.m_enemyUnits = Spar->getPerceptualState()->getEnemyUnits(GroupRectangularLocation(m_context.getGroup()));
  for(PersistentUnitGroup::const_iterator it=m_context.getGroup()->begin(); it != m_context.getGroup()->end(); ++it)
  {
    BWAPI::Unit* unit = *it;
    UnitCarefulAttackBehavior* newBehavior = new UnitCarefulAttackBehavior(&m_context, m_context.getCurrentPriority() * 2 + 1,unit,m_context.getGroup());
    newBehavior->zombifyOnTerminate();
    newBehavior->start();
  }
  findTarget();
  setTarget();
}

void GroupCarefulAttackBehavior::Engaging::onEnemyUnitDestroyed(void*)
{
  m_context.m_enemyUnits = Spar->getPerceptualState()->getEnemyUnits(GroupRectangularLocation(m_context.getGroup()));
  findTarget();
  setTarget();
}

void GroupCarefulAttackBehavior::Engaging::findTarget()
{
  BWAPI::Unit* nextTarget = NULL;
  if (m_context.m_enemyUnits.size() > 0)
  {
    BWAPI::Position center = m_context.getGroup()->getCenter();
    //BWAPI::Unit* nextTarget =  m_context.m_enemyUnits.getWeakest();
    //if(!nextTarget)
    nextTarget = GroupHelper::getNearest(m_context.m_enemyUnits, center);
  }
  if(!!nextTarget)
  {
    m_context.m_target = nextTarget;
    BWAPI::getIndividualUnitDestroyEvent(m_context.m_target).subscribe(&m_enemyUnitDestroyedEventHandler,0);  //Unsubscribe or the world will explode
  }
}

void GroupCarefulAttackBehavior::Engaging::setTarget()
{
  if(!!m_context.m_target)
  {
    m_context.forEachSubBehavior(SetTarget(m_context.m_target));
  }
}