#include "stdafx.h"
#include "InputHandler.h"

void InputHandler::AddKeyboardHandler( const Handler & handler, KeyboardEvent::EType type, int keycode, int flags )
{
	HandlersMap & map = m_handlers[ type ];
	for ( HandlersMap::iterator iter = map.begin(); iter != map.end(); ++iter )
	{
		if ( iter->second == handler )
		{
			map.erase( iter );
			break;
		}
	}

	KeyboardKey key;
	key.keycode = keycode;
	key.flags = flags;
	map.insert( std::make_pair( key, handler ) );
}

void InputHandler::RemoveKeyboardHandler( KeyboardEvent::EType type, int keycode, int flags )
{
	HandlersMap & map = m_handlers[ type ];
	for ( HandlersMap::iterator iter = map.begin(); iter != map.end(); ++iter )
	{
		if ( iter->first.keycode == keycode && iter->first.flags == flags )
		{
			map.erase( iter );
			break;
		}
	}
}

void InputHandler::RemoveKeyboardHandler( KeyboardEvent::EType type, const Handler & handler )
{
	HandlersMap & map = m_handlers[ type ];
	for ( HandlersMap::iterator iter = map.begin(); iter != map.end(); ++iter )
	{
		if ( iter->second == handler )
		{
			map.erase( iter );
			break;
		}
	}
}

void InputHandler::ProcessInput( IInput & input )
{
	input.BeginRead();
	while( true )
	{
		InputEvent e = input.GetEvent();
		if ( e.m_type == InputEvent::EV_INVALID )
			return;

		bool handled = false;

		if ( e.m_type == InputEvent::EV_KEYBOARD )
		{
			KeyboardKey key;
			key.keycode = e.m_keyboardEvent.m_keycode;
			key.flags = e.m_keyboardEvent.m_flags;
			
			HandlersMap::iterator handler = m_handlers[ e.m_keyboardEvent.m_type ].find( key );
			if ( handler != m_handlers[ e.m_keyboardEvent.m_type ].end() )
				handled = handler->second( e );
		}

		if ( handled )
			input.PopEvent();
		else
			input.NextEvent();
	}
}
