
#include <windows.h>
#include "Win32Keyboard.h"
#include "Win32Mouse.h"
#include "Win32EventQueue.h"
#include <Spectre/System/Log.h>

namespace sp {

bool Win32EventQueue::poll(Event& event)
{
	MSG msg;

	if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
		TranslateMessage(&msg);
		if (processMessage(msg, event) == 0) {
			return true;
		}
	}
	return false;
}

LRESULT Win32EventQueue::processMessage(MSG msg, Event& event)
{
	switch(msg.message) {
	case WM_QUIT :
		event.type = Event::Quit;
		return 0;
	// Input, Forward to devices.
	case WM_KEYDOWN :
	case WM_KEYUP :

		Log::debug("WM_KEY");

		if (Win32Keyboard::handleMessage(msg, event)) {
			// Keyboard did handle the message.
			return 0;
		}
		break;
	case WM_MOUSEMOVE :
	case WM_MOUSELEAVE :

		if (Win32Mouse::handleMessage(msg, event)) {
			// Mouse did handle the message.
			return 0;
		}
		break;
	case WM_LBUTTONDOWN :
	case WM_RBUTTONDOWN :
	case WM_MBUTTONDOWN :
	case WM_XBUTTONDOWN :

		SetCapture(msg.hwnd);

		if (Win32Mouse::handleMessage(msg, event)) {
			// Mouse did handle the message.
			return 0;
		}
		break;
	case WM_LBUTTONUP :
	case WM_RBUTTONUP :
	case WM_MBUTTONUP :
	case WM_XBUTTONUP :

		ReleaseCapture();

		if (Win32Mouse::handleMessage(msg, event)) {
			// Mouse did handle the message.
			return 0;
		}
		break;
	default :
		break;
	}

	// Message was not intercepted. Pass down to window.
	DispatchMessage(&msg);
	return 1;
}

} // namespace sp
