#include "stdafx.h"
#include "../../PerceptualState/PerceptualState.h" // for PerceptualState::getUnitRecord()
#include "../../SparAIContainer.h" // for SparAIContainer::getPerceptualState()
#include "Process.h"

size_t Process::s_id = 0;

const Process::InitialMode Process::WaitingToExecute;

const Process::InitialMode Process::WaitingForParentToExecute;

const Process::ExecutionMode Process::Executing;

const Process::TerminationMode Process::Success;
     
const Process::TerminationMode Process::ExternalEvent;

Process::~Process()
{
  assert(isTerminated());

  if (m_parent != NULL)
    m_parent->_onChildProcessDestroyed(m_positionInParent);

  m_destroyEvent.raise();
}

void Process::UnitRecordGroup::insert(BWAPI::Unit* unit)
{
  insert(Spar->getPerceptualState()->getUnitRecord(unit));
}

void Process::terminate(const TerminationMode& mode)
{
  if (!isTerminated())
  {
    m_currentMode = &mode;

    onEnd();

    m_terminateEvent.raise();

    reverseForEachChildProcess(TerminateProcess());

    removeUser();
  }
}

void Process::addUser() const
{
  ++m_useCount;
  if(m_parent)
    m_parent->addUser();
}

void Process::removeUser() const
{
  if (--m_useCount == 0 && m_zombifyOnTerminate)
    Component::addZombieComponent(this);

  if(m_parent)
    m_parent->removeUser();
}
