#include <PalmOS.h>
#include "SonyChars.h"
#include "T-Suite.h"

#define MenuCmdBarMaxPotentialButtons	8

#pragma mark ----------

static Boolean FTglGetInsPosition (UInt8 *Position)
{
	Boolean result = false;

	UInt8 num = MenuCmdBarMaxPotentialButtons;

	MenuCmdBarResultType resultType;
	
	do
	{
		Boolean t = MenuCmdBarGetButtonData (num - 1, NULL, &resultType, NULL, NULL);
		if (t && (resultType == menuCmdBarResultNone))
		{
			result = true;
			*Position = num;
			break;
		}
	}while (num-- > 0);

	return result;
}

static void FTglBtnShift (UInt8 numButtons, UInt8 shiftCount, UInt8 insPosition)
{
	UInt16 bitmapId;
	MenuCmdBarResultType resultType;
	UInt32 result;
	Char name[menuCmdBarMaxTextLength];

	UInt8 from = numButtons -1;
	
	for (UInt8 i = 0; i < (numButtons - insPosition); i++)
	{
		MenuCmdBarGetButtonData (from, &bitmapId, &resultType, &result, name);
		MenuCmdBarAddButton (from + shiftCount + 1, bitmapId, resultType, result, name);
		from--;
	}

	UInt8 to = insPosition;
	for (UInt8 i = 0; i < shiftCount; i++)
	{
		MenuCmdBarAddButton (to + 1, NULL, menuCmdBarResultNone, NULL, " ");
		to++;
	}
}

static UInt8 FTglGetNumButtons (void)
{
	UInt8 num = 0;
	
	do
	{
	}while (MenuCmdBarGetButtonData (num++, NULL, NULL, NULL, NULL));

	return num - 1;
}

#pragma mark ----------

Err FTglCmdBarKeyDownHandle (SysNotifyParamType *notifyParamsP)
{
	Boolean handled = true;

	UInt32 ftrValue;
	FtrGet (appFileCreator, ftr_appStatus, &ftrValue);
	TSuitePreferenceType *prefsP = (TSuitePreferenceType*)ftrValue;

	TSuitePreferenceType prefs;
		MemMove (&prefs, prefsP, sizeof (TSuitePreferenceType));

	EventType *event = (EventType*)notifyParamsP->notifyDetailsP;

// check FEP ModeChengeKey. If detect, erase toolbar immediately
	if (event->eType == Swap16 (keyDownEvent))
	{
		switch (Swap16 (event->data.keyDown.chr))
		{
		case vchrTsm1:
		case vchrTsm2:
		case vchrTsm3:
		case vchrTsm4:
			UInt32 prvTimeOut = TimGetTicks () + (SysTicksPerSecond () / 6);
			do
			{
			}while (prvTimeOut > TimGetTicks ());
			MenuEraseStatus (NULL);
			goto returnHandle;
		}
	}

// check CmdBarIsOpen
	if (!(MenuCmdBarGetButtonData (0, NULL, NULL, NULL, NULL)))
	{
		UInt16 cardNo;
		LocalID dbID;
		SysCurAppDatabase (&cardNo, &dbID);

		SysNotifyUnregister (cardNo, dbID, sysNotifyEventDequeuedEvent, FTglPriority);

		prefs.prevCmdBtnIndex = 0;

		handled = false;

		goto returnHandle;
	}

// To detect penDownEvent

	if (event->eType == Swap16 (penDownEvent))
	{
		return errNone;
	}

// To detect current shiftmode for 5.0 devices

	if (event->eType == nilEvent)
	{
		Boolean capsLock;
		Boolean numLock;
		UInt16 tempShift;
		Boolean autoShifted;
		GrfGetState (&capsLock, &numLock, &tempShift, &autoShifted);

		if (tempShift != prefs.tempShift)
		{
			Boolean upperShift;
			if (prefs.tempShift == grfTempShiftUpper)
				upperShift = true;
			else
				upperShift = false;
			GrfSetState (prefs.capsLock, prefs.numLock, upperShift);
			goto HiraKata;
		}
	}
	EvtSetNullEventTick(TimGetTicks () + 5);

// keyDownEvent handle
	if (event->eType != Swap16 (keyDownEvent))
	{
		handled = false;
		return errNone;
	}

	// FEP-key Handle------------------------------------
	Char *Result;
	WChar chr;

	switch (Swap16 (event->data.keyDown.chr))
	{
	case vchrCommand:	// NichiEi  "/"
		chr = vchrTsm4;
		Result = "日英";
		goto FEPModeHandled;

	case chrSpace:			// Henkan   " "
		chr = vchrTsm1;
		Result = "変換";
		goto FEPModeHandled;

	case '/':// os52
	case '.':// os52
	case '<':
	case '>':
	case ':':
	case ';':
HiraKata:
		chr = vchrTsm3;
		Result = "あア";
		goto FEPModeHandled;
	default:
UnHandled:
		handled = false;
		goto returnHandle;
	}

FEPModeHandled:
	EvtEnqueueKey (chr, 0, commandKeyMask);
	WbMtCmdBarKeyDownResDraw (&Result, prefs.numButtons);
	prefs.prevCmdBtnIndex = 0;
	event->eType = nilEvent;
	MenuEraseStatus (NULL);

returnHandle:
	prefs.prevCmdBtnIndex = prefs.prevCmdBtnIndex;
	DmWrite (prefsP, 0, &prefs, sizeof (TSuitePreferenceType));

	if (handled)
		notifyParamsP->handled = true;

	return errNone;
}

Err FTglCmdBarOpenedHandle (SysNotifyParamType *notifyParamsP)
{
	UInt16 cardNo;
	LocalID dbID;
	SysCurAppDatabase (&cardNo, &dbID);

	SysNotifyUnregister (cardNo, dbID, appFileCreator, FTglPriority);

	SysNotifyRegister (cardNo, dbID,
			sysNotifyEventDequeuedEvent, NULL, FTglPriority, (MemPtr)'FTgl');
//			sysNotifyEventDequeuedEvent, &FTglCmdBarKeyDownHandle, FTglPriority, (MemPtr)'FTgl');

	if (notifyParamsP->handled)
		return errNone;

	UInt32 ftrValue;
	FtrGet (appFileCreator, ftr_appStatus, &ftrValue);
	TSuitePreferenceType *prefsP = (TSuitePreferenceType*)ftrValue;

	TSuitePreferenceType prefs;
		MemMove (&prefs, prefsP, sizeof (TSuitePreferenceType));

	// to Add Dummy Button to Check cmdToolBar is Active
	UInt8 i;
	for (i = 0; i <= 8; i++)
	{
		prefs.numButtons = i;
		if (!(MenuCmdBarGetButtonData (i, NULL, NULL, NULL, NULL)))
		{
			break;
		}
	}

	if (i == 0)
	{
		MenuCmdBarAddButton (menuCmdBarOnRight,	0, menuCmdBarResultNone, 0, "   ");
	}

		prefs.keyControlHandled = IsOff;

// To detect current shiftmode for 5.0 devices
	GrfGetState (&prefs.capsLock, &prefs.numLock,
			&prefs.tempShift, &prefs.autoShifted);

	DmWrite (prefsP, 0, &prefs, sizeof (TSuitePreferenceType));

	WbMtCmdBarDrawRect ();

	notifyParamsP->handled = true;

	return errNone;
}

Err FTglCmdBarOpenHandle (SysNotifyParamType *notifyParamsP)
{
	UInt16 cardNo;
	LocalID dbID;
	SysCurAppDatabase (&cardNo, &dbID);

	SysNotifyRegister (cardNo, dbID,
			appFileCreator, NULL, FTglPriority, (MemPtr)'FTgl');
//			appFileCreator, &FTglCmdBarOpenedHandle, FTglPriority, (MemPtr)'FTgl');

	// Broadcast Custom Notify
	SysNotifyParamType notify;
	notify.notifyType = appFileCreator;
	notify.broadcaster = appFileCreator;
	notify.notifyDetailsP = NULL;
	notify.userDataP = notifyParamsP->userDataP;
	notify.handled = false;
	notify.reserved2 = NULL;

	SysNotifyBroadcastDeferred (&notify, 0);

	UInt32 ftrValue;
	FtrGet (appFileCreator, ftr_appStatus, &ftrValue);
	TSuitePreferenceType *prefsP = (TSuitePreferenceType*)ftrValue;

	if ((prefsP->AddNichiEiBtnF) || (prefsP->AddHiraKataBtnF) || (prefsP->AddHenkanBtnF))
	{
		LocalID FEPBtnDbID = DmFindDatabase (0, FEPBtnDbName);
		if (FEPBtnDbID)
		{
			UInt8 numButtons = FTglGetNumButtons ();

			UInt8 needNumSpace = 0;
				if (prefsP->AddNichiEiBtnF)
					needNumSpace++;
				if (prefsP->AddHiraKataBtnF)
					needNumSpace++;
				if (prefsP->AddHenkanBtnF)
					needNumSpace++;

			UInt8 availNumSpace = MenuCmdBarMaxPotentialButtons - numButtons;
			
			if (availNumSpace <= needNumSpace)
				needNumSpace = availNumSpace;
			
			if (needNumSpace != 0)
			{
				for (UInt8 i = needNumSpace; i > 0; i--)
					MenuCmdBarAddButton (menuCmdBarOnLeft,	0, menuCmdBarResultNone, 0, " ");

				UInt8 insPosition = prefsP->BtnInsPosition;

				if (insPosition == 5)
					insPosition = numButtons;

				if (numButtons < insPosition)
					insPosition = numButtons;

				if (insPosition != numButtons)
					FTglBtnShift (numButtons, needNumSpace, insPosition);
			}

			DmOpenRef FEPBtnDbRef;
			DmSearchResource ('Tbmp', Btn_NichiEiBitmapFamily, NULL, &FEPBtnDbRef);
			if (!FEPBtnDbRef)
			{
				DmOpenDatabase (0, FEPBtnDbID, dmModeLeaveOpen);
			}

			UInt8 InsPosition;

			if (prefsP->AddNichiEiBtnF == IsOn)
				if (FTglGetInsPosition (&InsPosition))
					MenuCmdBarAddButton (InsPosition, Btn_NichiEiBitmapFamily,
						menuCmdBarResultChar, vchrTsm4, "日英");
			if (prefsP->AddHiraKataBtnF == IsOn)
				if (FTglGetInsPosition (&InsPosition))
					MenuCmdBarAddButton (InsPosition, Btn_HiraKataBitmapFamily,
						menuCmdBarResultChar, vchrTsm3, "あア");
			if (prefsP->AddHenkanBtnF == IsOn)
				if (FTglGetInsPosition (&InsPosition))
					MenuCmdBarAddButton (InsPosition, Btn_HenkanBitmapFamily,
						menuCmdBarResultChar, vchrTsm1, "変換");
		}
	}

	notifyParamsP->handled = true;

	return errNone;
}