#include <kamui2.h>
#include <shinobi.h>
#include <ctype.h>
#include "dispstrex.h"
#include "key.h"
#include "command.h"

char Prevkey = 0xFF;

unsigned char ConvertOneCharactor(unsigned char code, KMBOOLEAN bShift)
{
	if(code >= 0x04 && code <= 0x1D)
	{
		if(bShift)
		{
			return toupper('a' + (code - 0x04));
		}
		else
		{
			return 'a' + (code - 0x04);				/* Ascii code */
		}
	}

	if(code >= 0x1E && code <= 0x26)
	{
		return '1' + (code - 0x1E);				/* Number Charactor */
	}

	if(code == 0x27) return '0';
	if(code == 0x28) return 0x0A;				/* Return Code */
	if(code == 0x2A) return 0x08;				/* Return BackSpace */
	if(bShift)
	{
		switch(code)
		{
			case 0x2C:
				return ' ';
			case 0x2D:
				return '=';
			case 0x38:
				return '?';
			case 0x36:
				return '<';
			case 0x37:
				return '>';
			case 0x87:
			case 0x89:
				return '_';
		}
	}
	else
	{
		switch(code)
		{
			case 0x2C:
				return ' ';
			case 0x2D:
				return '-';
			case 0x38:
				return '/';
			case 0x36:
				return ',';
			case 0x37:
				return '.';
			case 0x87:
			case 0x89:
				return '\\';
		}
	}

	return 0;
}

void ConvertKeyCodeToASCII(unsigned char* Data, PDS_KEYBOARD* kbd)
{
	if(kbd->key[0])
	{
		Data[0] = ConvertOneCharactor(kbd->key[0], kbd->ctrl & (PDD_KEY_CTRL_LSHIFT | PDD_KEY_CTRL_RSHIFT));
		if(Data[0] == Prevkey)
		{
			Data[0] = '\0';
			return;
		}
		Prevkey = Data[0];
		Data[1] = '\0';
	}
	else
	{
		Prevkey = 0xFF;
		Data[0] = '\0';
		return;
	}
}

void KeyBoardServer(void)
{
    const PDS_KEYBOARD* kbd;
	unsigned char Input[5];
	char CommandLine[80];

	kbd = pdKbdGetData(PDD_PORT_A0);
	ConvertKeyCodeToASCII(Input, kbd);
	switch(Input[0])
	{
		case '\0':
		{
			break;					/* No Action */
		}
		case 0x0A:
		{
			PRINTOUT(("%c", 0x08));	/* Back Space */
			txt_GetCommandLineString(CommandLine);		/* Execute Command */
			PRINTOUT(("%s", Input));					/* Return */

			ExecuteCommand(CommandLine);

			PRINTOUT((">"));
			txt_SetBlink( TRUE );
			PRINTOUT(("_"));
			txt_SetBlink( FALSE );
			break;
		}
		default:
		{
			PRINTOUT(("%c", 0x08));	/* Back Space */
			PRINTOUT(("%s", Input));
			txt_SetBlink( TRUE );
			PRINTOUT(("_"));
			txt_SetBlink( FALSE );
			break;
		}
	}
}
