#include <pspkernel.h>
#include <pspdebug.h>
#include <pspdisplay.h>
#include <pspctrl.h>
#include <stdlib.h>
#include <string.h>
#include <pikeylib.h>

#include "../sdk/pikeytypes.h"

/* Define the module info section */
PSP_MODULE_INFO("PIKEYTEST", 0x1000, 1, 1);
PSP_MAIN_THREAD_ATTR(0);
PSP_MAIN_THREAD_STACK_SIZE_KB(64);

/* Define printf, just to make typing easier */
#define printf	pspDebugScreenPrintf

int done = 0;

int main(void)
{
	pspDebugScreenInit();
	int ii;

	printf("piKey sample.\n");

	initPikey();

	sceKernelDelayThread(1000000);

	printf("piKey is detected as : %s\n", isPikeyLoaded() ? "RUNNING" : "NOT RUNNING");

	requestExclusive();

	setMode(PIKEY_KEYMODE_KEYPRESS);

	sceKernelDelayThread(1000000);

	pspDebugScreenClear();

	pspDebugScreenSetXY(0, 5);
	printf("Waiting for keysto be pressed. Press ESC to exit...\n\n");

	while(!done)
	{
		sceKernelDelayThread(1000);  // don't tight-loop
		sceDisplayWaitVblank();

		// clear old display
		pspDebugScreenClear();

		pspDebugScreenSetXY(0, 5);
		printf("Waiting for keys to be pressed. Press ESC to exit...\n\n");

#if 0
		pspDebugScreenSetXY(0,7);
		for (ii = 7; ii < 20; ii++)
		{
			printf("                              \n");
		}
#endif

		// nothing to do if no keys pressed.
		if (numKeysPressed() == 0)
		{
			continue;
		}

		pspDebugScreenSetXY(0,7);
		for (ii = 0; ii < KEY_MAX; ii++)
		{
			if (isKeyPressed(ii))
			{
				printf("Pressed scancode: %d\n", ii);
			}
		}

		int ctrl, alt, shift;
		getMetaKeys(&alt, &ctrl, &shift);

		pspDebugScreenSetXY(0, 20);
		printf("  %s  %s  %s\n",
			     ctrl?  "CTRL"  : "    ",
					 alt?   "ALT"   : "   ",
					 shift? "SHIFT" :	"     ");

		if (isKeyPressed(KEY_ESC))
		{
			done = 1;
		}
	}

	printf("\nEXIT\n");

	releaseExclusive();

	sceKernelExitGame();
	return 0;
}
