#include <windows.h>
#include <jni.h>
#include <aygshell.h>
#include <assert.h>
#include "wce-peer.h"
#include "resource.h"
#include <gnu_java_awt_peer_wce_WCEMenuBarPeer.h>

/**
 * メニューバー上にあるメニューに付与するユニークID
 * 開始数値は IDM_DUMMY にしている（これは重要）
 */
static LONG g_menu_id = IDM_DUMMY;

static DWORD get_menu_id() {
	return InterlockedIncrement(&g_menu_id);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuBarPeer
 * Method:    addNativeMenu
 * Signature: (IILjava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEMenuBarPeer_addNativeMenu(JNIEnv *env, jobject peer_obj, jint menuBarWindowHandle, jint menuHandle, jstring label) {
	BOOL b;
	int count;
	TBBUTTON tb = {0};
	_TCHAR* buff = get_string_chars(env, label);

	tb.iBitmap = I_IMAGENONE;
	tb.idCommand = get_menu_id();
	tb.fsState = TBSTATE_ENABLED;
	tb.fsStyle = TBSTYLE_DROPDOWN | TBSTYLE_AUTOSIZE | TBS_NOTHUMB;
	tb.dwData = (DWORD) menuHandle;
	tb.iString = (INT_PTR) buff;
	
	count = SendMessage((HWND) menuBarWindowHandle, TB_BUTTONCOUNT, 0, 0);
	b = SendMessage((HWND) menuBarWindowHandle, TB_INSERTBUTTON, count, (LPARAM) &tb);

	free(buff);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuBarPeer
 * Method:    disposeNativeMenuBar
 * Signature: (I)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEMenuBarPeer_disposeNativeMenuBar(JNIEnv *env, jobject peer_obj, int menuBarWindowHandle) {
	int i;
	for (i = 0; i < MAX_MENUS; ++i) {
		if (! SendMessage((HWND) menuBarWindowHandle, TB_DELETEBUTTON, 0, 0)) {
			break;
		}
	}
}
	
/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuBarPeer
 * Method:    deleteNativeMenuByHandle
 * Signature: (II)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEMenuBarPeer_deleteNativeMenuByHandle(JNIEnv *env, jobject peer_obj, int menuBarWindowHandle, int menuHandle) {
	int i;
	TBBUTTON tb;
	for (i = 0; i < MAX_MENUS; ++i) {
		if (! SendMessage((HWND) menuBarWindowHandle, TB_GETBUTTON, (WPARAM) i, (LPARAM) &tb)) {
			break;
		}
		if (tb.dwData == (DWORD) menuHandle) {
			SendMessage((HWND) menuBarWindowHandle, TB_DELETEBUTTON, (WPARAM) i, 0);
			break;
		}
	}
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuBarPeer
 * Method:    deleteNativeMenuByPosition
 * Signature: (II)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEMenuBarPeer_deleteNativeMenuByPosition(JNIEnv *env, jobject peer_obj, int menuBarWindowHandle, int index) {
	SendMessage((HWND) menuBarWindowHandle, TB_DELETEBUTTON, (WPARAM) index, 0);
}