#include "stdafx.h"
#include "Detection.h"
#include "../../SparAIContainer.h"
#include "../../Utils/BresenhamCircle.h"
#include "../../PerceptualState/PerceptualState.h"
#include "../UnitRecord/UnitRecord.h"

void Detection::update(InfluenceMap<Detection>& map)
{
  map.reset();

  if (map.getPlayer() == BWAPI::Broodwar->enemy())
  {
    std::pair<Map::unit_const_iterator, Map::unit_const_iterator> enemyUnits = Spar->getPerceptualState()->getMap()->getEnemyUnits();
    update(map, enemyUnits.first, enemyUnits.second);
  }
}

template<class T>
void doUpdate(InfluenceMap<Detection> &map, T * unit, unsigned int cost)
{
  BWAPI::UnitType type = unit->getType();
  if(type.isDetector())
  {
    BWAPI::TilePosition pos = unit->getTilePosition();
    Detection::UpdateDetection func(map, pos.x(), pos.y(), cost);
    BresenhamCircle(func, (type.sightRange() / TILE_SIZE) + 1, true);
  }
}

void Detection::update(InfluenceMap<Detection>& map, BWAPI::Unit* unit)
{
  doUpdate(map, unit, 3);
}

void Detection::update(InfluenceMap<Detection>& map, const UnitRecord* unit)
{
  if (unit->isAccessible())
  {
    update(map, unit->getUnit());
  }
  else
  {
    doUpdate(map, unit, unit->getType().isBuilding() ? 3 : 1);
  }
}