#if defined(_WIN32)

#include "Controller.hpp"
#include <windows.h>
#include <Xinput.h>

#pragma comment (lib, "xinput.lib")

Controller* Controller::controller = NULL;

Controller::Controller(void)
:button(0)
,touch(false)
{
}

Controller::~Controller(void)
{
}

void Controller::Initialize(void)
{
	Controller::controller = new Controller;
}

void Controller::Finalize(void)
{
	if(Controller::controller != NULL)
	{
		delete Controller::controller;
		Controller::controller = NULL;
	}
}

Controller& Controller::GetInstance()
{
	return *Controller::controller;
}

void Controller::Reset(void)
{
	this->button = 0;
}

void Controller::Update(void)
{
	this->button = 0;
	XINPUT_STATE state;
	ZeroMemory(&state, sizeof(XINPUT_STATE));
	if(XInputGetState(0, &state) == ERROR_SUCCESS)
	{
		if(state.Gamepad.wButtons & XINPUT_GAMEPAD_A)
		{
			this->button |= BUTTON_1;
		}
		if(state.Gamepad.wButtons & XINPUT_GAMEPAD_B)
		{
			this->button |= BUTTON_2;
		}
		if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP)
		{
			this->button |= BUTTON_UP;
		}
		if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN)
		{
			this->button |= BUTTON_DOWN;
		}
		if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT)
		{
			this->button |= BUTTON_LEFT;
		}
		if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT)
		{
			this->button |= BUTTON_RIGHT;
		}
	}
	if(GetAsyncKeyState('Z') & 0x8000)
	{
		this->button |= BUTTON_1;
	}
	if(GetAsyncKeyState('X') & 0x8000)
	{
		this->button |= BUTTON_2;
	}
	if(GetAsyncKeyState(VK_UP) & 0x8000)
	{
		this->button |= BUTTON_UP;
	}
	if(GetAsyncKeyState(VK_DOWN) & 0x8000)
	{
		this->button |= BUTTON_DOWN;
	}
	if(GetAsyncKeyState(VK_LEFT) & 0x8000)
	{
		this->button |= BUTTON_LEFT;
	}
	if(GetAsyncKeyState(VK_RIGHT) & 0x8000)
	{
		this->button |= BUTTON_RIGHT;
	}
}

unsigned int Controller::GetButton(void)
{
	return this->button;
}

#endif
