
#include <Spectre/System/Log.h>

#include "X11EventQueue.h"
#include "Xlib.h"
#include "X11Keyboard.h"
#include "X11Mouse.h"
#include "X11WindowEventHandler.h"

namespace sp {

bool X11EventQueue::poll(Event& event)
{
	::Display* disp = Xlib::getDisplay();
	Atom del_win = Xlib::getAtom("WM_DELETE_WINDOW");
	Atom wm_proto = Xlib::getAtom("WM_PROTOCOLS");

	if (XPending(disp)) {
		XEvent xevent;

		XNextEvent(disp, &xevent);

		switch(xevent.type) {
		case ClientMessage:
			Log::info("X11: ClientMessage");

			if (xevent.xclient.message_type == wm_proto
				&& xevent.xclient.data.l[0] == del_win) {

				event.type = Event::Quit;
				return true;
			}
			break;
		case ResizeRequest:
			Log::info("X11: Resize event");
			break;
		case KeyPress:
		case KeyRelease:
			if (X11Keyboard::handleMessage(&xevent.xkey, event)) {
				return true;
			}
			break;
		case ButtonPress:
		case ButtonRelease:
		case MotionNotify:
			if (X11Mouse::handleMessage(&xevent, event)) {
				return true;
			}
			break;
		default:
			// Pass to window.
			Log::info("X11: Window Event");
			X11WindowEventHandler::process(disp, xevent);
		}
	}

	return false;
}

} //namespace sp
