#include "stdafx.h"
#include "BuildPylonsProcess.h"
#include "../Layer3Script.h"
#include "../../../../PerceptualState/PerceptualState.h"

// TODO: re-power unpowered buildings

void BuildPylonsProcess::run()
{
  const int supplyForOneRound = Layer3Script::getInstance().countSupplyForOneRoundTroops();
  const int supplyToAcquire = (BWAPI::Broodwar->self()->supplyUsed() + supplyForOneRound) -
                              (BWAPI::Broodwar->self()->supplyTotal() + m_buildPylons.size() * BWAPI::UnitTypes::Protoss_Pylon.supplyProvided());
  if (BWAPI::Broodwar->self()->supplyTotal() != BWAPI::MAX_SUPPLY &&
      supplyToAcquire >= 0)
  {
    const size_t nbPylons = (supplyToAcquire + BWAPI::UnitTypes::Protoss_Pylon.supplyProvided()) / BWAPI::UnitTypes::Protoss_Pylon.supplyProvided();
    for (size_t i = 0; i < nbPylons; ++i)
    {
      Build* build = Layer3Script::getInstance().getLayer2().instantiateBuild(
        this,
        PRIORITY_BUILD_PYLONS, 
        Spar->getPerceptualState()->getMap(), 
        BWAPI::UnitTypes::Protoss_Pylon);
      m_buildPylons.add(build);
      build->start();
    }
  }

  if (Spar->getPerceptualState()->getMap()->getNbCompletedOwnUnits(BWAPI::UnitTypes::Protoss_Pylon) > 0 && 
      m_buildPylons.size() == 0 && 
      Layer3Script::getInstance().getLayer2().needsAdditionalPylons())
  {
    Build* build = Layer3Script::getInstance().getLayer2().instantiateBuild(
      this,
      PRIORITY_BUILD_PYLONS, 
      Spar->getPerceptualState()->getMap(), 
      BWAPI::UnitTypes::Protoss_Pylon);
    m_buildPylons.add(build);
    build->start();
  }
}
