///////////////////////////
//	File: CSGD_Dispatcher.cpp
//	Author:	Eric Green
//	Purpose: CSGD_Dispatcher function definitions


#include "CSGD_Dispatcher.h"

CSGD_Dispatcher* CSGD_Dispatcher::m_pInstance;
CSGD_Dispatcher* CSGD_Dispatcher::GetInstance()
{
	if(!m_pInstance)
		m_pInstance = new CSGD_Dispatcher;
	return m_pInstance;
}

void CSGD_Dispatcher::UnregisterClient(IListener* pClient)
{
	multimap<EVENTID,IListener*>::iterator iter;
	iter = m_Clients.begin();

	while(iter != m_Clients.end())
	{
		if((*iter).second == pClient)
			iter = m_Clients.erase(iter);
		else
			iter++;
	}
	
}
//register client
void CSGD_Dispatcher::RegisterClient(EVENTID eventID, IListener *pClient)
{
	if(!pClient) return;

	//register (push) our client into the client list.
	m_Clients.insert(make_pair(eventID, pClient));

}

void CSGD_Dispatcher::DispatchEvent(CEvent *pEvent)
{
	//make an interator that will iterate through all of our
	//clients that shoudl be receiving an event.
	pair<multimap<EVENTID,IListener*>::iterator,
		multimap<EVENTID,IListener*>::iterator> range;

	//find all clients that should reviece this event.
	range = m_Clients.equal_range(pEvent->GetEventID());

	//go through my list of clients that can receive this event.
	for (multimap<EVENTID,IListener*>::iterator iter = range.first;
		iter != range.second; iter++)
	{
		//pass the event to this client.
		(*iter).second->HandleEvent(pEvent);
	}
}

void CSGD_Dispatcher::SendEvent(EVENTID eventID, void *pParam)
{
	CEvent newEvent;
	newEvent.SetEventParams(eventID, pParam);
	m_Events.push_back(newEvent);
}


void CSGD_Dispatcher::ProcessEvents()
{
	while(m_Events.size())
	{
		DispatchEvent(&m_Events.front());
		m_Events.pop_front();
	}
}
	

