#include "stdafx.h"
#include "CorsairVsScourge.h"
#include "../../PerceptualState/Locations/Static/Shape/RectangularLocation.h"
#include "../../PerceptualState/InfluenceMap/InfluenceMap.h"
#include "../../PerceptualState/PerceptualState.h"

Location * getFullMap()
{
  BWAPI::Position topLeft(TILE_SIZE, TILE_SIZE);
  BWAPI::Position bottomRight((BWAPI::Broodwar->mapWidth() - 2) * TILE_SIZE, (BWAPI::Broodwar->mapHeight() - 2) * TILE_SIZE);
  return new RectangularLocation(topLeft, bottomRight);
}

CorsairVsScourgeScenario::CorsairVsScourgeScenario()
    : m_timerEvent(*this, Scheduler::FSM_SCHEDULING_PRIORITY, 2, 2)
    , m_onTerminated(*this)
    , m_onKilled(*this)
    , m_behavior(0)
    , m_corsair(0)
    , m_fullMap(*this, getFullMap())
  {}

void CorsairVsScourgeScenario::onTimer()
{
  const InfluenceMapRef<Threat>::map_ptr th = Spar->getPerceptualState()->getEnemyThreat();
  if(!m_behavior && th->getData(m_corsair->getTilePosition()).futureAir > 0)
  {
    m_behavior = new FleeingAirUnitBehavior(this, 100, m_corsair, m_fullMap);
    m_subscriberId = m_behavior->getTerminateEvent().subscribe(&m_onTerminated, m_behavior);
    
    m_behavior->zombifyOnTerminate();
    m_behavior->start();
  }
}

void CorsairVsScourgeScenario::onTerminated(void * raw)
{
  if(m_behavior == static_cast<FleeingAirUnitBehavior *>(raw))
  {
    m_behavior->getTerminateEvent().unsubscribe(m_subscriberId);
    m_behavior = 0;
  }
}

void CorsairVsScourgeScenario::onKilled(void *)
{
  m_timerEvent.deactivate();
}

void CorsairVsScourgeScenario::onSparStarted(void*)
{
  const std::set<BWAPI::Unit *> &units = BWAPI::Broodwar->getAllUnits();
  for(std::set<BWAPI::Unit *>::const_iterator it = units.begin(); it != units.end(); ++it)
  {
    BWAPI::Unit * unit = *it;
    if(unit->getType() == BWAPI::UnitTypes::Protoss_Corsair)
      m_corsair = unit;
    else if(unit->getType() == BWAPI::UnitTypes::Zerg_Scourge)
      m_scourges.insert(unit);
  } 

  BWAPI::getIndividualUnitDestroyEvent(m_corsair).subscribe(&m_onKilled, 0);

  m_timerEvent.activate();
}
