#include "stdafx.h"
#include "L2Harass.h"
#include "../Layer2Managers.h"

L2Harass::L2Harass(const Process* parent, unsigned int priority, const PersistentUnitGroup* initialGroup, Location* location)
  : Harass(parent, priority, initialGroup, location)
  , L2GroupTacticalAction(parent, priority, initialGroup)
  , GroupTacticalAction(parent, priority, initialGroup)
  , TacticalAction(parent, priority)
  , Process(parent)
  , m_harassmentBehaviors(*this)
  , m_onHarassmentBehaviorTerminated(*this)
{
}

void L2Harass::onUnitAddedToGroup(void*, BWAPI::Unit* unit)
{
  unused(unit);
  // TODO
}

void L2Harass::onUnitRemovedFromGroup(void*, BWAPI::Unit* unit)
{
  unused(unit);
  // TODO
}

void L2Harass::onStartImplementation()
{
  L2GroupTacticalAction::onStartImplementation();

  const PersistentUnitGroup* group = getGroup();
  for (PersistentUnitGroup::const_iterator it = group->begin(); it != group->end(); ++it)
  {
    assert((*it)->getType() == BWAPI::UnitTypes::Protoss_Corsair);

    CorsairHarassmentBehavior* harassmentBehavior = new CorsairHarassmentBehavior(this, 100, *it, m_location);
    m_harassmentBehaviors.add(harassmentBehavior);
    harassmentBehavior->getTerminateEvent().subscribe(&m_onHarassmentBehaviorTerminated, harassmentBehavior);
    harassmentBehavior->start();
  }
}

void L2Harass::onHarassmentBehaviorTerminated(void*)
{
  if (m_harassmentBehaviors.size() <= 1)
  {
    terminate(Success);
  }
}

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

void L2Harass::onEndImplementation()
{
  L2GroupTacticalAction::onEndImplementation();
}
