#include "stdafx.h"

#include "Component.h"
#include "../PerceptualState/PerceptualState.h" // for PerceptualState::getUnitRecord()
#include "../SparAIContainer.h" // for SparAIContainer::getPerceptualState()
#include "Utils.h"

/////////////////////////////////////////////////////////////////////

std::string Component::getName() const
{
  return extractSimpleClassName(typeid(*this));
}

void Component::deleteZombieComponents()
{
  for (std::list<const Component*>::const_iterator it = s_zombieComponents.begin();
       it != s_zombieComponents.end();
       ++it)
  {
    delete (*it);
  }
  s_zombieComponents.clear();
}

#ifdef _DEBUG_COMPONENT
#include "EventHandler.h"
#include "../Scheduler/Scheduler.h"

Component::~Component()
{
  std::stringstream ss1;
  ss1 << "ERROR Component::~Component(): Make sure to unsubscribe event handler \"%s\" from event \"%s\" before its owner \"" << typeid(*this).name() << "\" is deleted.";
  _verifyPendingSubscriptions(ss1.str().c_str());

  std::stringstream ss2;
  ss1 << "ERROR Component::~Component(): Make sure to deactivate task \"%s\" before its owner \"" << typeid(*this).name() << "\" is deleted.";
  _verifyPendingTasks(ss2.str().c_str());
}

void Component::_verifyPendingSubscriptions(const char* error) const
{
  for (std::set<const EventHandlerBase*>::const_iterator it = m_eventHandlers.begin(); it != m_eventHandlers.end(); ++it)
  {
    (*it)->_printErrorIfStillSubscribed(error);
  }
}

/**
 * @brief Outputs an error message for each pending task associated to this component.
 *        The caller assumes the component should have deactivated all its tasks at this point.
 */
void Component::_verifyPendingTasks(const char* error) const
{
  for (std::set<const SchedulerTask*>::const_iterator it = m_tasks.begin(); it != m_tasks.end(); ++it)
  {
    (*it)->printErrorIfStillActivated(error);
  }
}

#endif
