#include "stdafx.h"
#include "L2AttackMove.h"
#include "../Layer2Managers.h"
#include "../../../../PerceptualState/Locations/Static/Shape/CoordinatesLocation.h"

void L2AttackMove::onStartImplementation()
{
  m_event.activate();
  L2GroupTacticalAction::onStartImplementation();
  //getGroup()->attackMove(m_target);
  m_groupAttackBehavior = new GroupAttackBehavior(this, 100, getGroup(), new CoordinatesLocation(m_target));
  m_groupAttackBehavior->start();
}

void L2AttackMove::onCancelImplementation()
{
  L2GroupTacticalAction::onCancelImplementation();
  terminate(Cancelled);
}

void L2AttackMove::onEndImplementation()
{
  L2GroupTacticalAction::onEndImplementation();
  m_event.deactivate();
}

void L2AttackMove::onUnitAddedToGroup(void*, BWAPI::Unit*)
{
}

void L2AttackMove::onUnitRemovedFromGroup(void*, BWAPI::Unit*)
{
}

void L2AttackMove::onTimeout()
{
  if(m_groupAttackBehavior==NULL)
  {
    // TODO: get the termination mode from the FSM
    terminate(Success);
  } else {
    //If 1 unit is idle at target
    std::set<BWAPI::Unit*> units = BWAPI::Broodwar->getUnitsInRadius(m_target,3*TILE_SIZE);
    bool idleUnit = false;
    bool actionEnded = false;
    for(std::set<BWAPI::Unit*>::const_iterator it = units.begin() ; it != units.end() ; ++it)
    {
      if(getGroup()->find(*it) != getGroup()->end())
      {
        if((*it)->isIdle())
        {
          idleUnit = true;
        }
      }
    }
    //find new target
    if(idleUnit)
    {
      std::pair<AutoPopulatedLocation::building_const_iterator,AutoPopulatedLocation::building_const_iterator> eBuildings = m_location->getEnemyBuildings();
      if(eBuildings.first == eBuildings.second)
      {
        std::pair<AutoPopulatedLocation::unit_const_iterator,AutoPopulatedLocation::unit_const_iterator> eUnits = m_location->getEnemyUnits();
        {
          if(eUnits.first == eUnits.second)
          {
            actionEnded = true;
          }
          else
          {
            m_target = (*eUnits.first)->getPosition();
            m_groupAttackBehavior->externalTerminate();
            m_groupAttackBehavior = new GroupAttackBehavior(this, 100, getGroup(), new CoordinatesLocation(m_target));
            m_groupAttackBehavior->start();             
          }
        }     
      }
      else
      {
        m_target = (*eBuildings.first)->getPosition();
        m_groupAttackBehavior->externalTerminate();
        m_groupAttackBehavior = new GroupAttackBehavior(this, 100, getGroup(), new CoordinatesLocation(m_target));
        m_groupAttackBehavior->start(); 
        //getGroup()->attackMove(m_target);
      }

    }
    //if no new target action terminated
    if(actionEnded)
    {
      terminate(Success);
    }
    //If new not terminated reactivte on timeout
    else
    {
      m_event.activate();
    }
  }
}