#include "..\inc\mymouse.h"
#include "myLevel.h"

myMouse::myMouse(void)
{
	m_di		= NULL;
	m_diDevice	= NULL;
}

myMouse::~myMouse(void)
{
	clean();
}

bool myMouse::init(HINSTANCE hInstance, HWND hwnd)
{
	HRESULT hr;
	hr = DirectInput8Create(hInstance,
							DIRECTINPUT_VERSION,
							IID_IDirectInput8,
							(void**)&m_di,
							NULL);
	if(FAILED(hr)) return false;

	hr = m_di->CreateDevice(GUID_SysMouse,&m_diDevice,NULL);
	if(FAILED(hr)) return false;

	hr = m_diDevice->SetDataFormat(&c_dfDIMouse);
	if(FAILED(hr)) return false;

	hr = m_diDevice->SetCooperativeLevel(hwnd,DISCL_FOREGROUND|DISCL_NONEXCLUSIVE);
	if(FAILED(hr)) return false;

	hr = m_diDevice->Acquire();
	if(FAILED(hr)) return false;
	
	return true;
}

void myMouse::poll()
{
	DIMOUSESTATE ms;
	HRESULT hr;
	hr = m_diDevice->GetDeviceState(sizeof(ms),(LPVOID)&ms);
	if(FAILED(hr))
	{
		m_diDevice->Acquire();
		return;
	}

	myLevel::getCurrent()->handleMessage(myLevel::MYMT_ROTATELEFTRIGHT,&(ms.lX));
	myLevel::getCurrent()->handleMessage(myLevel::MYMT_TILTUPDOWN,&(ms.lY));
}

void myMouse::clean()
{
	if(m_diDevice != NULL)
	{
		m_diDevice->Release();
		m_diDevice = NULL;
	}
	if(m_di != NULL)
	{
		m_di->Release();
		m_di = NULL;
	}
}
