// EventManager.C

#include "xrmlP.H"
#include "List.H"
#include "EventManager.H"

namespace xrml {

PoolImpl(EventManager)

void EventManager::init(class world *world)
{
  EventManager::world = world;
}

inline void EventManager::queue(const class interfaceMember *event)
{
  if (!nextEvent) {
    nextEvent = lastEvent = new event_list(event);
  } else {
    lastEvent = lastEvent->append(event);
  }
  nrEvents++;
}

inline void EventManager::dispatch(const class interfaceMember *event) const
{
  // temporarily set world time to timestamp of event so that all
  // events in the generated event cascade have same timestamp.
  double saved_time = world->time;
  world->time = event->timestamp;

  event->dispatch();

  world->time = saved_time;
}

void EventManager::post(const class SFNode *srcnode, const class interfaceMember *event)
{
  if (dispatch_immediately) {
    dispatch(event);
  } else {
    queue(event);
  }
}

inline event_list* EventManager::take_event(void)
{
  event_list *e = nextEvent;
  if (nextEvent) {
    nextEvent = nextEvent->remove((event_list*)0);
    if (!nextEvent) lastEvent = 0;
    nrEvents--;
  }
  return e;
}

void EventManager::dispatch_all(void)
{
  dispatch_immediately = true;

  event_list *e;
  while ((e = take_event()) != 0) {
    dispatch(*e);
    delete e;
  }

  dispatch_immediately = false;
}

int EventManager::nrQueuedEvents(void) const
{
  return nrEvents;
}

} // namespace xrml

