#include <windows.h>
#include <jni.h>
#include <assert.h>
#include "wce-peer.h"
#include <gnu_java_awt_peer_wce_WCEMenuItemPeer.h>


/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuItemPeer
 * Method:    addNativeTo
 * Signature: (ILjava/lang/String;)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_WCEMenuItemPeer_addNativeTo(JNIEnv *env, jobject peer_obj, jint parentMenuHandle, jstring label) {
	BOOL b;
	UINT flags;
	WORD id = create_menu_item_id((HMENU) parentMenuHandle);
	MENUITEMINFO mii = {0};
	_TCHAR* buff = get_string_chars(env, label);

	if (_tcslen(buff) == 1 && *buff == _T('-')) {
		// ラベルが '-' の場合にはセパレータを意味する
		flags = MF_SEPARATOR;
	} else {
		flags = MF_STRING;
	}
	b = AppendMenu((HMENU) parentMenuHandle,
				flags, 
				id,
				buff);
	free(buff);
	
	// メニューアイテム情報を設定する
	mii.cbSize = sizeof(MENUITEMINFO);
	mii.fMask = MIIM_DATA;
	mii.dwItemData = (DWORD) peer_obj;
	b = SetMenuItemInfo((HMENU) parentMenuHandle,
						id,
						FALSE,
						&mii);
	return (jint) id;
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuItemPeer
 * Method:    setNativeEnabled
 * Signature: (IIZ)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEMenuItemPeer_setNativeEnabled(JNIEnv *env, jobject peer_obj, jint parentMenuHandle, jint commandID, jboolean enabled) {
	EnableMenuItem((HMENU) parentMenuHandle, commandID, MF_BYCOMMAND | ((enabled == JNI_TRUE) ? MF_ENABLED : MF_GRAYED));
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuItemPeer
 * Method:    setNativeLabel
 * Signature: (IILjava/lang/String;)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEMenuItemPeer_setNativeLabel(JNIEnv *env, jobject peer_obj, jint parentMenuHandle, jint commandID, jstring label) {
	MENUITEMINFO info = {0};
	_TCHAR* buff = get_string_chars(env, label);

	info.cbSize = sizeof(MENUITEMINFO);
	info.fMask = MIIM_TYPE;

	// dwTypeData のみを書き換えて設定しなおす
	GetMenuItemInfo((HMENU) parentMenuHandle, commandID, FALSE, &info);
	info.dwTypeData = buff;
	SetMenuItemInfo((HMENU) parentMenuHandle, commandID, FALSE, &info);
	free(buff);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCEMenuItemPeer
 * Method:    deleteNativeMenuItemFrom
 * Signature: (II)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCEMenuItemPeer_deleteNativeMenuItemFrom(JNIEnv *env, jobject peer_obj, jint parentMenuHandle, int commandID) {
	DeleteMenu((HMENU) parentMenuHandle, commandID, FALSE);
	delete_menu_item_id((WORD) commandID);
}