/***************************************************************************/
/** @file       input_raw_keyboard.cpp
	@brief      キーボード操作受付
	@author     shom
	@internal
****************************************************************************/

#include "pch_core.h"

#include "input_raw_keyboard.h"

#include "core/input/input_keyboard_def.h"


using namespace input_keyboard_def;


/***************************************************************************
	cinput_raw_keyboard
****************************************************************************/

cinput_raw_keyboard::cinput_raw_keyboard( LPDIRECTINPUT8 p_dinput )
:
cinput_raw_base( p_dinput )
{
	m_p_dinput = p_dinput;
}

b32 cinput_raw_keyboard::Initialize( HWND h_wnd )
{
	HRESULT	hr;

	///--
	hr	= m_p_dinput->CreateDevice(
			GUID_SysKeyboard,
			&m_p_device,
			NULL
			);
	if( FAILED( hr ) || !m_p_device )
	{
		DEBUG_BREAK();
	}
	///--

	///--
	if( FAILED( m_p_device->SetDataFormat(
				   &c_dfDIKeyboard	//キーボード
				   ) ) )
	{
		DEBUG_BREAK();
	}
	///--

	///--
	if( FAILED( m_p_device->SetCooperativeLevel(
					h_wnd,
					DISCL_NONEXCLUSIVE	// フォアグラウンドモード
					| DISCL_FOREGROUND	// 非排他モード
					) ) )
	{
		DEBUG_BREAK();
	}
	///--

	return ( cinput_raw_base::Initialize( h_wnd ) );
}

void	cinput_raw_keyboard::Finalize()
{
}

u32		cinput_raw_keyboard::GetState()	const
{
	if( m_p_device == NULL )
	{
		return KEY_ERR;
	}

	HRESULT hr = S_OK;

	///--
	BYTE dik_state[ 256 ] = {0};

	hr = m_p_device->GetDeviceState( sizeof( dik_state ), dik_state );

	if( FAILED( hr ) )
	{
		do
		{
			hr = m_p_device->Acquire();
			if( hr != DIERR_INPUTLOST )
			{
				break;
			}
#if !0
			break;
#endif
		}
		while( true );


		if( FAILED( hr ) )
		{
			return KEY_ERR;
		}
	}
	///--

	///--
	u32 key_state = 0;

#define	DIK_KEY__INPUT_RAW_KEYBOARD( _dik, _key )	\
													\
	if( dik_state[ _dik ] & 0x80 )					\
	{												\
		key_state |= KEY_##_key##;					\
	}												\

#include "input_raw_keyboard.h"
#undef DIK_KEY__INPUT_RAW_KEYBOARD

#define	DIK__INPUT_RAW_KEYBOARD( _key )		\
											\
	if( dik_state[ DIK_##_key ] & 0x80 )	\
	{										\
		key_state |= KEY_##_key##;			\
	}										\

#include "input_raw_keyboard.h"
#undef DIK__INPUT_RAW_KEYBOARD

	if( ( dik_state[ DIK_BACK ] & 0x80 ) ||
		( dik_state[ DIK_DELETE ] & 0x80 )
		)
	{
		key_state |= KEY_DELBS;
	}

	return key_state;
	///--
}

