#include "stdafx.h"
#include "UpgradeMonitoringProcess.h"
#include "../../World/UpgradeTypeObject.h"

UpgradeMonitoringProcess::UpgradeMonitoringProcess(const Process* parent, BWAPI::Unit* building, UpgradeTypeObject* upgrade)
  : InBuildingMonitoringProcessT(parent, building)
  , InBuildingMonitoringProcess(parent, building)
  , MonitoringProcess(parent)
  , m_upgrade(upgrade)
{
}

void UpgradeMonitoringProcess::_output(std::ostream& out) const
{
  out << "Upgrade in progress: " << *m_upgrade;
}

bool UpgradeMonitoringProcess::testCompletion()
{
  if (BWAPI::Broodwar->self()->getUpgradeLevel(m_upgrade->getUpgrade()) >= m_upgrade->getLevel())
  {
    m_upgrade->setTechAcquired();
    terminate(Success);
  }
  else if (!m_building->isUpgrading())
  {
    terminate(Cancelled);
  }
  return isTerminated();
}

void UpgradeMonitoringProcess::setNewTimeout(bool error)
{
  if (error)
  {
    SPAR_LOG(LogTypes.GENERAL_ERROR, "Upgrade not finished when it should: %s", toString(m_upgrade).c_str());
  }
  m_timeoutEvent.setWaitingTimeBeforeExecution(m_building->getRemainingUpgradeTime()+3);
}

void UpgradeMonitoringProcess::cancel()
{
  m_building->cancelUpgrade();

  m_timeoutEvent.deactivate();
  m_timeoutEvent.setWaitingTimeBeforeExecution(1);
  m_timeoutEvent.activate();
}
