
#include <Platform/PlatformInput.h>
#include <Spectre/Input/Keyboard.h>
#include <Spectre/Input/Mouse.h>
#include <Spectre/Input/InputEvent.h>
#include <Spectre/Input/InputDevice.h>
#include <Spectre/Input/InputModule.h>

InputModule::InputModule(PlatformInput *platform) :
m_platform	(platform)
{
	// Let user "install" devices?
	m_mouse = m_platform->createMouse();
	m_keyboard = m_platform->createKeyboard();

	addInputDevice(m_mouse);
	addInputDevice(m_keyboard);
}

InputModule::~InputModule()
{
	InputDeviceVec::iterator it;

	for(it = m_devices.begin(); it != m_devices.end(); it++) {
		delete (*it);
	}
}

void InputModule::addInputDevice(InputDevice *device)
{
	device->init();

	m_devices.push_back(device);
}

void InputModule::registerListener(InputListener* listener)
{
	m_listeners.push_back(listener);
}

void InputModule::removeListener(InputListener* listener)
{
	
}

Mouse* InputModule::getMouse()
{
	return m_mouse;
}

Keyboard* InputModule::getKeyboard()
{
	return m_keyboard;
}

void InputModule::postInputEvent(const InputEvent& event)
{
	if (m_buffer.size() < 128) {
		m_buffer.push_back(event);
	}
}

void InputModule::update()
{
	InputDeviceVec::iterator it;

	m_platform->update();

	// Update all devices.
	for(it = m_devices.begin(); it != m_devices.end(); it++) {

		(*it)->update(this);
	}

	// Dispatch all events to listeners.
	dispatch();
}

void InputModule::dispatch()
{
	std::deque<InputEvent>::iterator it;

	for(it = m_buffer.begin(); it != m_buffer.end(); it++) {

		const InputEvent& event = *it;

		// Call listeners.
		std::vector<InputListener*>::iterator it;
		for(it = m_listeners.begin(); it != m_listeners.end(); it++) {

			(*it)->onInputEvent(event);
		}
	}

	m_buffer.clear();
}
