#include "DIMouse.h"

namespace HPL {
namespace DirectX {
DIMouse::DIMouse() :DIBase(),m_pDIDevice(NULL){

	ZeroMemory(&this->m_CurrentState, sizeof(DIMOUSESTATE2) );
	ZeroMemory(&this->m_PreviousState, sizeof(DIMOUSESTATE2) );

}
DIMouse::~DIMouse() {
	m_pDIDevice->Unacquire();
}

HRESULT DIMouse::initDevice( HINSTANCE hInstance, HWND hWnd
							//, DWORD dwMode
							) {
	HRESULT hr = S_OK;

	hr = createDInput(hInstance );
	if(FAILED(hr ) ) {
		return hr;
	}

	hr = m_pDInput->CreateDevice( GUID_SysMouse, & this->m_pDIDevice, NULL );
	if(FAILED( hr ) ) {
		return hr;
	}

	hr = m_pDIDevice->SetDataFormat( &c_dfDIMouse2 );
	if(FAILED(hr)) {
		return hr;
	}

	hr = m_pDIDevice->SetCooperativeLevel( hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND );
	if( FAILED(hr ) ) {
		return hr;
	}

	// 軸モード設定（相対値モード）
	DIPROPDWORD diprop;
	diprop.diph.dwSize			= sizeof(diprop);
	diprop.diph.dwHeaderSize	= sizeof(diprop.diph);
	diprop.diph.dwObj			= 0;
	diprop.diph.dwHow			= DIPH_DEVICE;
	diprop.dwData				= DIPROPAXISMODE_REL;	//相対値モード

	hr = m_pDIDevice->SetProperty( DIPROP_AXISMODE, &diprop.diph ) ;
	if( FAILED( hr ) ) {
		return hr;
	}

	// 入力制御開始
	m_pDIDevice->Acquire();

	return hr;

}
void DIMouse::set_AxisMode( DWORD dwMode ) {
	m_pDIDevice->Unacquire();
	DIPROPDWORD diprop;
	diprop.diph.dwSize			= sizeof(diprop);
	diprop.diph.dwHeaderSize	= sizeof(diprop.diph);
	diprop.diph.dwObj			= 0;
	diprop.diph.dwHow			= DIPH_DEVICE;
	diprop.dwData = dwMode;
	m_pDIDevice->SetProperty( DIPROP_AXISMODE, &diprop.diph ) ;
	m_pDIDevice->Acquire();
}

VOID DIMouse::set_Acquire( BOOL bFlag ) {
	if( m_pDIDevice == NULL ) {
		return;
	}
	if( bFlag ) {
		m_pDIDevice->Acquire();
	}else {
		m_pDIDevice->Unacquire();
	}
}

HRESULT DIMouse::get_Key()
{
	HRESULT hr = S_OK;

	if( m_pDIDevice != NULL ) {
		DIMOUSESTATE2 dims;


		hr = m_pDIDevice->GetDeviceState( sizeof( DIMOUSESTATE2), &dims );
		if(SUCCEEDED(hr ) ) {
			memcpy(&this->m_PreviousState, &this->m_CurrentState, sizeof(DIMOUSESTATE2 ) );
			memcpy(&this->m_CurrentState, &dims, sizeof(DIMOUSESTATE2 ) );
		} else {
			m_pDIDevice->Acquire();
		}
	}

	return hr;
}
DIMOUSESTATE2* DIMouse::get_CurrentState() {
	return &this->m_CurrentState;
}
DIMOUSESTATE2* DIMouse::get_PreviousState() {
	return &this->m_PreviousState;
}
}
}
