/*
	Lan Wars.
	Copyright (c) 2009, Darragh Coy.
	All rights reserved.
	Original work(s), source code & author(s) details available at: http://www.darraghcoy.com

	Redistribution and use in source and binary forms, with or without modification, are permitted 
	provided that the following conditions are met:

		* 	Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* 	Redistributions in binary form must reproduce the above copyright notice, this list of 
			conditions and the following disclaimer in the documentation.
		* 	Neither the name of the author nor the names of contributors may be used to endorse or 
			promote products derived from this software without specific prior written permission.
		* 	The use of any third party libraries, modules or data files provided with the source 
			form of the program must follow and respect the individual licensing terms of these 
			components. You do not have permission to modify or circumvent the licensing terms for 
			provided third party components unless the third party licenses specifically allow this. 
			If you do not agree to the terms of provided third party components then you do not have 
			permission to use them in your derived work(s).
		* 	The terms of this license do not apply to separate (but related) distributions if supplied 
			by the author(s), only to the contents of this source distribution, derived works, and the 
			binaries produced by either modified or unmodified versions of the source code. The terms 
			of this license do not also apply to any third party libraries or components provided with 
			the source distribution. Such third party elements are licensed under their own separate 
			agreements.

	THIS SOFTWARE IS PROVIDED BY DARRAGH COY ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
	ARE DISCLAIMED. IN NO EVENT SHALL DARRAGH COY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
	OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 
	OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 
	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

//=====================================================================================================================
/// @brief		Class representing the keyboard. Provides functions for querying for keyboard input as well as 
///				Virtual Key to ascii key conversions.
//=====================================================================================================================

#include "Precompiled.h"
#include "Input\Keyboard.h"

using namespace Game;

//=====================================================================================================================
/// @brief		Tells if a particular keyboard key is pressed
/// @param		key_code - virtual keycode of the key
/// @returns	True if it the given key is pressed
//=====================================================================================================================

bool Keyboard::IsKeyPressed( Key key_code )
{
    // Return whether the key is pressed or not

    return ( (GetAsyncKeyState((int)key_code) & 0x80000000) != 0 ? true : false );
}

//=====================================================================================================================
/// @brief		Tells if a particular keyboard key is toggled or switched on, like the capslock or numlock keys
/// @param		key_code - virtual keycode of the key
/// @returns	True if it the given toggle key is toggled
//=====================================================================================================================

bool Keyboard::IsKeyToggled( Key key_code )
{
    // Get the key state:

    int state = GetKeyState((int)key_code);

    // If the first bit is one then the key is toggled:

    return ( state & 1 ) != 0;
}

//=====================================================================================================================
/// @brief		Translates the given virtual keyboard key to its ascii value
/// @param		key_code - virtual keycode of the key
/// @returns	Ascii representation of the key, or 0 if there is no representation. Shift key for example is not an
///				Ascii character!
//=====================================================================================================================

char Keyboard::KeyToAscii( Key key_code )
{
    // Try and get the current state of the keyboard

    static char kbstate[256];

    if ( GetKeyboardState( (PBYTE) kbstate ) == 0 ) 
	{
		// Couldn't get the state: return 0

		return 0;
	}

    // Hold the translated key in this array

    char translated_keys[256];

    // Get the hardware scan code of the key

    int scan_code = MapVirtualKey
    (
        (int)key_code,	// virtual key code to convert
        0				// translate to a scan code
    );

    // If the scan conversion failed return 0:

    if ( scan_code == 0 ) return 0;

    // Translate the key and save the result of the translation

	int result = ::ToAscii
    (
        (int)key_code,				// virtual key code
        scan_code,					// key scan code
        (PBYTE) kbstate,			// keyboard state array
        (LPWORD) translated_keys,	// buffer for translate key(s)
        0							// whether a menu is active - 0 if not
    );

    // If the result was 1 then we have got an ascii key and it should be returned otherwise return 0 for failure:

    if ( result == 1 ) return translated_keys[0]; else return 0;
}

//=====================================================================================================================
/// @brief		Generates keyboard events for the given polled event listener, by comparing a current and previous 
///				state for the keyboard.
/// @param		listener - listener that receives the keyboard events
/// @param		previous_state - previous state of the keyboard
/// @param		current_state - current state of the keyboard
/// @pre		The given event listener must not be null
/// @remarks	This function only generates virtual key events. To generate key typed events with ascii characters,
///				use GenerateCharEvents().
/// @remarks	Unfortunately this function is incapable of generating repeated keys, but should suffice for most 
///				simple event based input requirements.
//=====================================================================================================================

void Keyboard::GenerateEvents( PolledEventListener * listener , const State & previous_state , const State & current_state )
{
	// Do a broad comparison using integers
	
	for ( unsigned i = 0 ; i < 64 ; ++i )
	{
		// See if these 4 chars are equal:
		
		if ( * (((unsigned*)(previous_state.m_keys)) + i ) != * (((unsigned*)(current_state.m_keys)) + i ) )
		{
			// Ok these four keys are not equal somewhere: get the index in the array of chars we are looking at
			
			unsigned base_index = i * 4;
			
			// Compare these 4 keys:
			
			for ( int j = 0 ; j < 4 ; j++ )
			{						
				// Calculate index of the key
				
				unsigned key_index = base_index + j;
				
				// See if pressed or released
			
				if ( previous_state.IsKeyPressed((Key)(key_index)) )
				{
					// Check for released key:
					
					if ( current_state.IsKeyReleased((Key)(key_index)) )
					{
						// Key now released: generate event
						
						listener->OnKeyboardReleased((Key)(key_index));
					}
				}
				else
				{
					// Check for pressed key:
					
					if ( current_state.IsKeyPressed((Key)(key_index)) )
					{
						// Key now pressed: generate event
						
						listener->OnKeyboardPressed((Key)(key_index));
					}			
				}
			}
		}
	}
}

//=====================================================================================================================
/// @brief		Generates keyboard typed events for the given polled event listener, by comparing a current and previous 
///				state for the keyboard
/// @param		listener - listener that receives the keyboard events
/// @param		previous_state - previous state of the keyboard
/// @param		current_state - current state of the keyboard
/// @pre		The given event listener must not be null
/// @remarks	This function only generates only ascii character typed events. Fir virtual keys use GenerateEvents().
/// @remarks	Unfortunately this function is incapable of generating repeated keys, but should suffice for most 
///				simple event based input requirements.
//=====================================================================================================================

void Keyboard::GenerateCharEvents( PolledEventListener * listener , const State & previous_state , const State & current_state )
{
	// Do a broad comparison using integers
	
	for ( unsigned i = 0 ; i < 64 ; ++i )
	{
		// See if these 4 chars are equal:
		
		if ( * (((unsigned*)(previous_state.m_keys)) + i ) != * (((unsigned*)(current_state.m_keys)) + i ) )
		{
			// Ok these four keys are not equal somewhere: get the index in the array of chars we are looking at
			
			unsigned base_index = i * 4;
			
			// Compare these 4 keys:
			
			for ( int j = 0 ; j < 4 ; j++ )
			{						
				// Calculate index of the key
				
				unsigned key_index = base_index + j;
				
				// See if pressed or released
			
				if ( previous_state.IsKeyReleased((Key)(key_index)) )
				{
					// Check for newly pressed key:
					
					if ( current_state.IsKeyPressed((Key)(key_index)) )
					{
						// Key was just pressed: get a hardware scan code of the key						

						int scan_code = MapVirtualKey
						(
							key_index,		// virtual key code to convert
							0				// translate to a scan code
						);

						// If the scan conversion failed do nothing

						if ( scan_code != 0 )
						{
							// Hold the translated key in this array

							char translated_keys[256];
							
							// Convert to ascii
							
							int result = ::ToAscii
							(
								key_index,						// virtual key code
								scan_code,						// key scan code
								(PBYTE) current_state.m_keys,	// keyboard state array
								(LPWORD) translated_keys,		// buffer for translate key(s)
								0								// whether a menu is active - 0 if not
							);
							
							// See if that succeeded:
							
							if ( result == 1 )
							{
								// Call the keyboard typed event on the listener with the typed key
								
								listener->OnKeyboardTyped( translated_keys[0] );
							}
						
						}	// end if converted to scan code ok
						
					}	// end if key is now pressed
					
				}	// end if key was previously released
				
			}	// end for all 4 characters in the 4 char group
			
		}	// end if this 4 char group has changed
		
	}	// end for all 64 4 char groups in the keyboard state
}
