#include <PalmOS.h>
#include "SonyChars.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))
	{
		if (prefs.keyControlHandled == IsOn)
			WbMtCmdBarExtendTimeOut (event);
	}

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

	// other-key Handle------------------------------------
	switch (Swap16 (event->data.keyDown.chr))
	{
	case vchrJogPushRepeat:
	case vchrJogPush:
		WbMtCmdBarExtendTimeOut (event);
		goto returnHandle;

	case chrLineFeed:
	case vchrJogRelease:
		goto Select;

	case chrLeftArrow:
	case vchrJogDown:
		goto Left;

	case chrRightArrow:
	case vchrJogUp:
		goto Right;

	case chrBackspace:
	case chrDownArrow:
	case vchrJogBack:
	case vchrJogPushedDown:
		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;
	event->eType = nilEvent;
	MenuEraseStatus (NULL);
	goto returnHandle;

Select:
	prefs.keyControlHandled = IsOff;
	if (!(prefs.prevCmdBtnIndex == 0) &&
		!(prefs.prevCmdBtnIndex == prefs.numButtons + 1))
	WbMtCmdBarSendBtnResult (prefs.prevCmdBtnIndex);
	prefs.prevCmdBtnIndex = 0;
	event->eType = nilEvent;
	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, &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, &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;
}