#include <z_env.hpp>
#if defined(USE_UGL_INPUT)
#include <z_event.hpp>
#include <uglinput.h>
#include <z_device.hpp>

UGL_INPUT_Q_ID InputQueueGet(void);
bool InputQueuePoll(ugl_input_event &event, ZafEventType type);
void InputQueueRelease();

int queueCount = 0;
bool eventReady = false;
ugl_input_event holdEvent;

UGL_INPUT_Q_ID InputQueueGet(void)
{
	if (queueCount == 0)
		uglInputQStandardQCreate(100);
	queueCount++;
	return (uglInputQ);
}

void InputQueueRelease()
{
	if (--queueCount <= 0)
	{
		uglInputQStandardQDelete();
		uglInputQ = 0;
		eventReady = false;
		queueCount = 0;
	}
}

bool InputQueuePoll(ugl_input_event &event, ZafEventType type)
{
	bool retVal = false;
	UGL_STATUS status = UGL_STATUS_OK;
	if (!eventReady)
		status = uglInputQStandardQEventGet( 0, &holdEvent );
	if (status == UGL_STATUS_OK)
	{
		eventReady = true;
		retVal = true;
		switch (holdEvent.id)
		{
			// Mouse event
			case UGL_INPUT_EVENT_TYPE_ABSOLUTE_POINTER:
			case UGL_INPUT_EVENT_TYPE_INCREMENTAL_POINTER:
			if (type == E_MOUSE)
			{
				event = holdEvent;
				eventReady = false;
			}
			else
				retVal = false;
			break;

			// Keyboard event
			case UGL_INPUT_EVENT_TYPE_KEYBOARD:
			if (type == E_KEY)
			{
				event = holdEvent;
				eventReady = false;
			}
			else
				retVal = false;
			break;

			default:
				retVal = false;
				eventReady = false;
		}
	}
	if (!eventReady)
	{
		status = uglInputQStandardQEventGet( 0, &holdEvent );
		if (status == UGL_STATUS_OK)
			eventReady = true;
	}
	return (retVal);
}
#endif
