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

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

static void WbMtCmdBarExtendTimeOut (EventType *event)
{
	event->eType = (eventsEnum)Swap16 (keyDownEvent);
	event->data.keyDown.chr = 0; 
	event->data.keyDown.keyCode = 0;
	event->data.keyDown.modifiers = 0; 
}

static void WbMtCmdBarDrawButtons (UInt8 curCmdBtnIndex, UInt8 numButtons)
{
	WinPushDrawState ();
	WinHandle PrevDrawWindowH = WinSetDrawWindow (WinGetDisplayWindow ());

	Coord DisplayExtentX;
	Coord DisplayExtentY;
	WinGetDisplayExtent (&DisplayExtentX, &DisplayExtentY);
	RectangleType CmdBarRect;

	CmdBarRect.topLeft.x = 0 + 1;
	CmdBarRect.topLeft.y = DisplayExtentY - 19 + 1;
	CmdBarRect.extent.x = DisplayExtentX - 3;
	CmdBarRect.extent.y = 19 - 3;

	UInt16 maxWidth = DisplayExtentX - 14 - (17 * numButtons);

	RectangleType CmdBarNameRect;
	CmdBarNameRect.topLeft.x = CmdBarRect.topLeft.x + 11;
	CmdBarNameRect.topLeft.y = CmdBarRect.topLeft.y;
	CmdBarNameRect.extent.x = maxWidth;
	CmdBarNameRect.extent.y = 16;
	
	WinSetForeColor (UIColorGetTableEntryIndex (UIMenuFill));
	WinDrawRectangle (&CmdBarNameRect, 0);

	WinSetForeColor (UIColorGetTableEntryIndex (UIMenuSelectedFill));
	WinSetBackColor (UIColorGetTableEntryIndex (UIMenuFill));
	WinSetUnderlineMode (grayUnderline);
	FntSetFont (boldFont);

	if ((curCmdBtnIndex == 0) || (curCmdBtnIndex > numButtons))
	{
		WinDrawChars ("   ", 3, CmdBarRect.topLeft.x + 11, CmdBarRect.topLeft.y + 1);
	}
	else
	{
		Char BtnName[20];
		MenuCmdBarGetButtonData (curCmdBtnIndex - 1, NULL, NULL, NULL, BtnName);
		WinDrawTruncChars (BtnName, StrLen (BtnName),
						CmdBarRect.topLeft.x + 11, CmdBarRect.topLeft.y + 1, maxWidth);
	}

	Int16 buttonIndex = 0;
	UInt16 bitmapId;
	MemHandle bitmapMh;
	MemPtr bitmapP;
	do
	{
		MenuCmdBarGetButtonData (buttonIndex, &bitmapId, NULL, NULL, NULL);
		bitmapMh = DmGetResource ('Tbmp', bitmapId);
		if (bitmapMh == NULL)
			bitmapMh = DmGetResource ('abmp', bitmapId);
		
		if (bitmapMh != NULL)
		{
			bitmapP = MemHandleLock (bitmapMh);
			RectangleType BmpRect;
			BmpRect.topLeft.x = CmdBarRect.topLeft.x + CmdBarRect.extent.x - (17 * (buttonIndex + 1));
			BmpRect.topLeft.y = CmdBarRect.topLeft.y;
			BmpRect.extent.x = 17;
			BmpRect.extent.y = 16;
			if (buttonIndex == (curCmdBtnIndex - 1))
			{
				WinSetForeColor (UIColorGetTableEntryIndex (UIMenuSelectedFill));
				WinDrawRectangle (&BmpRect,	0);
				WinSetForeColor (UIColorGetTableEntryIndex (UIMenuFill));
				WinSetBackColor (UIColorGetTableEntryIndex (UIMenuSelectedFill));
			}
			else
			{
				WinSetForeColor (UIColorGetTableEntryIndex (UIMenuFill));
				WinDrawRectangle (&BmpRect,	0);
				WinSetForeColor (UIColorGetTableEntryIndex (UIMenuFrame));
				WinSetBackColor (UIColorGetTableEntryIndex (UIMenuFill));
			}
			WinSetDrawMode (winPaint);
			BmpRect.topLeft.y++;
			WinPaintBitmap ((BitmapPtr)bitmapP, BmpRect.topLeft.x, BmpRect.topLeft.y);
			MemHandleUnlock (bitmapMh);
		}
		buttonIndex++;
	}while (buttonIndex < numButtons);
	WinSetDrawWindow (PrevDrawWindowH);
	WinPopDrawState ();
}

/*static*/ void WbMtCmdBarKeyDownResDraw (Char **nameP, UInt8 numButtons)
{
	WinPushDrawState ();
	WinHandle PrevDrawWindowH = WinSetDrawWindow (WinGetDisplayWindow ());

	Coord DisplayExtentX;
	Coord DisplayExtentY;
	WinGetDisplayExtent (&DisplayExtentX, &DisplayExtentY);
	RectangleType CmdBarRect;

	CmdBarRect.topLeft.x = 0 + 1;
	CmdBarRect.topLeft.y = DisplayExtentY - 19 + 1;
	CmdBarRect.extent.x = DisplayExtentX - 3;
	CmdBarRect.extent.y = 19 - 3;

	UInt16 maxWidth = DisplayExtentX - 14 - (17 * numButtons);

	RectangleType CmdBarNameRect;
	CmdBarNameRect.topLeft.x = CmdBarRect.topLeft.x + 11;
	CmdBarNameRect.topLeft.y = CmdBarRect.topLeft.y;
	CmdBarNameRect.extent.x = maxWidth;
	CmdBarNameRect.extent.y = 16;
	
	WinSetForeColor (UIColorGetTableEntryIndex (UIMenuFill));
	WinDrawRectangle (&CmdBarNameRect, 0);

	WinSetForeColor (UIColorGetTableEntryIndex (UIFieldFepUnderline));
	WinSetBackColor (UIColorGetTableEntryIndex (UIMenuFill));
	WinSetUnderlineMode (grayUnderline);
	FntSetFont (boldFont);

	WinDrawTruncChars (*nameP, StrLen (*nameP),
			CmdBarRect.topLeft.x + 11, CmdBarRect.topLeft.y + 1, maxWidth);

	WinSetDrawWindow (PrevDrawWindowH);
	WinPopDrawState ();
	
	UInt32 prvTimeOut = TimGetTicks () + (SysTicksPerSecond () / 6);
	do
	{
	}while (prvTimeOut > TimGetTicks ());
}

static void WbMtCmdBarSendBtnResult (UInt8 curCmdBtnIndex)
{
	EventType newEvent;
	MemSet (&newEvent, sizeof (newEvent), 0);

	SysNotifyParamType notifyParams;

	MenuCmdBarResultType resultType;
	UInt32 result;
	Char name[20];

	MenuCmdBarGetButtonData (curCmdBtnIndex - 1, NULL, &resultType, &result, name);

	switch (resultType)
	{
	case menuCmdBarResultChar:
		newEvent.eType = keyDownEvent;
		newEvent.data.keyDown.chr = result;
		newEvent.data.keyDown.modifiers = commandKeyMask;
		EvtAddEventToQueue (&newEvent);
		break;

	case menuCmdBarResultMenuItem:
		newEvent.eType = menuEvent;
		newEvent.data.menu.itemID = result;
		EvtAddEventToQueue (&newEvent);
		break;

	case menuCmdBarResultNotify:
		notifyParams.notifyType = result;
		notifyParams.broadcaster = sysFileCSystem;
		notifyParams.notifyDetailsP = NULL;
		notifyParams.userDataP = NULL;
		notifyParams.handled = false;
		SysNotifyBroadcastDeferred (&notifyParams, sizeof (notifyParams));
		break;
	}
}

/*static*/ void WbMtCmdBarDrawRect (void)
{
	WinPushDrawState ();
	WinHandle PrevDrawWindowH = WinSetDrawWindow (WinGetDisplayWindow ());

	Coord DisplayExtentX;
	Coord DisplayExtentY;
	WinGetDisplayExtent (&DisplayExtentX, &DisplayExtentY);
	RectangleType CmdBarRect;

	CmdBarRect.topLeft.x = 0 + 1;
	CmdBarRect.topLeft.y = DisplayExtentY - 19 + 1;
	CmdBarRect.extent.x = DisplayExtentX - 3;
	CmdBarRect.extent.y = 19 - 3;

	WinSetForeColor (UIColorGetTableEntryIndex (UIFormFrame));
	WinDrawRectangleFrame (popupFrame, &CmdBarRect);

	WinSetDrawWindow (PrevDrawWindowH);
	WinPopDrawState ();
}

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

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

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

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

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

		SysNotifyUnregister (cardNo, dbID, sysNotifyEventDequeuedEvent, WbMtPriority);

		prefs.prevCmdBtnIndex = 0;
		prefs.keyControlHandled = IsOff;

		handled = false;

		goto returnHandle;
	}

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

// nilEvent Block CommandBar Timeout
	if ((event->eType == Swap16 (nilEvent)) ||
		 ((event->eType == Swap16 (keyDownEvent)) && (event->data.keyDown.chr == Swap16 (vchrResetAutoOff))))
	{
		if (prefs.keyControlHandled == IsOn)
		{
			WbMtCmdBarExtendTimeOut (event);
			EvtResetAutoOffTimer ();
		}
	}

// penDownEvent handle
	if (event->eType == Swap16 (penDownEvent))
	{
		prefs.prevCmdBtnIndex = 0;
		prefs.keyControlHandled = IsOff;
		WbMtCmdBarDrawButtons (0, prefs.numButtons);
		handled = false;
		goto returnHandle;
	}

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

	EventType newEvent;
	MemSet (&newEvent, sizeof (newEvent), 0);

	// 5-way navigation Handle---------------------------------
	newEvent.eType =  (eventsEnum)Swap16 (event->eType);
	newEvent.data.keyDown.chr = Swap16 (event->data.keyDown.chr);
	newEvent.data.keyDown.keyCode = Swap16 (event->data.keyDown.keyCode);
	newEvent.data.keyDown.modifiers = Swap16 (event->data.keyDown.modifiers);

//	Boolean NavUpEvent = false;
	if (NavKeyPressed(&newEvent, Left))
		goto NavLeft;
	if (NavKeyPressed(&newEvent, Right))
		goto NavRight;
//	if (NavKeyPressed(&newEvent, Up))	// this event can detect vchrPageUp
//	{	NavUpEvent = true;
//		goto NavUp;}
	if (NavKeyPressed(&newEvent, Down))
		goto NavDown;
	if (NavSelectPressed(&newEvent))
		goto NavSelect;
	if (IsFiveWayNavEvent(&newEvent))
	{
		handled = true;
		MemSet (event, sizeof(EventType), 0);
		WbMtCmdBarExtendTimeOut (event);
		goto returnHandle;
	}

	// other-key Handle------------------------------------
	switch (Swap16 (event->data.keyDown.chr))
	{
	case chrLineFeed:
NavSelect:
		goto Select;

	case chrLeftArrow:
NavLeft:
		goto Left;

	case chrRightArrow:
NavRight:
		goto Right;

	case chrBackspace:
	case chrDownArrow:
NavDown:
		goto Hide;

	default:
		handled = false;
	}
	goto returnHandle;

Left:
	prefs.keyControlHandled = IsOn;
	if ((prefs.prevCmdBtnIndex > prefs.numButtons) ||
		(prefs.prevCmdBtnIndex == 0))
	{
		prefs.prevCmdBtnIndex = 1;
	}
	else
	{
		prefs.prevCmdBtnIndex++;
		if (prefs.prevCmdBtnIndex == prefs.numButtons + 1)
			prefs.prevCmdBtnIndex = 1;
	}
	goto moveKeyHandle;

Right:
	prefs.keyControlHandled = IsOn;
	if ((prefs.prevCmdBtnIndex > prefs.numButtons) ||
		(prefs.prevCmdBtnIndex == 0))
	{
		prefs.prevCmdBtnIndex = prefs.numButtons;
	}
	else
	{
		prefs.prevCmdBtnIndex--;
		if (prefs.prevCmdBtnIndex == 0)
			prefs.prevCmdBtnIndex = prefs.numButtons;
	}
	goto moveKeyHandle;

Hide:
	prefs.keyControlHandled = IsOff;
	prefs.prevCmdBtnIndex = 0;
	MemSet (event, sizeof(EventType), 0);
	MenuEraseStatus (NULL);
	goto returnHandle;

Select:
	prefs.keyControlHandled = IsOff;
	if (!(prefs.prevCmdBtnIndex == 0) &&
		!(prefs.prevCmdBtnIndex == prefs.numButtons + 1))
	WbMtCmdBarSendBtnResult (prefs.prevCmdBtnIndex);
	prefs.prevCmdBtnIndex = 0;
	MemSet (event, sizeof(EventType), 0);
	MenuEraseStatus (NULL);
	goto returnHandle;

moveKeyHandle:
	WbMtCmdBarDrawButtons (prefs.prevCmdBtnIndex, prefs.numButtons);
	EvtFlushKeyQueue ();
	WbMtCmdBarExtendTimeOut (event);

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

	if (handled)
		notifyParamsP->handled = true;

	return errNone;
}

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

	SysNotifyUnregister (cardNo, dbID, appFileCreator, WbMtPriority);

	SysNotifyRegister (cardNo, dbID,
			sysNotifyEventDequeuedEvent, NULL, WbMtPriority, (MemPtr)'WbMt');
//			sysNotifyEventDequeuedEvent, &WbMtCmdBarKeyDownHandle, WbMtPriority, (MemPtr)'WbMt');

	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;

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

	WbMtCmdBarDrawRect ();

	notifyParamsP->handled = true;

	return errNone;
}

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

	SysNotifyRegister (cardNo, dbID,
			appFileCreator, NULL, WbMtPriority, (MemPtr)'WbMt');
//			appFileCreator, &WbMtCmdBarOpenedHandle, WbMtPriority, (MemPtr)'WbMt');

	// 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);

	notifyParamsP->handled = true;

	return errNone;
}