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

#define DEFAULT_ROWS	5
#define DEFAULT_COLS	30

/*
 * Class:     gnu_java_awt_peer_wce_WCETextAreaPeer
 * Method:    createNativeTextArea
 * Signature: (IIIIII)I
 */
JNIEXPORT jint JNICALL
Java_gnu_java_awt_peer_wce_WCETextAreaPeer_createNativeTextArea(JNIEnv *env,
																jobject peer_obj,
																jint parentWindowHandle,
																jint x,
																jint y,
																jint width,
																jint height,
																jint scrollbarVisibility) {
	peer_obj = (*env)->NewGlobalRef(env, peer_obj);
	return (jint) create_native_text_area(peer_obj, (HWND) parentWindowHandle, x, y, width, height, scrollbarVisibility);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextAreaPeer
 * Method:    insertNative
 * Signature: (ILjava/lang/String;I)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCETextAreaPeer_insertNative(JNIEnv *env, jobject peer_obj, jint windowHandle, jstring text, jint pos) {
	HWND hwnd = (HWND) windowHandle;
	_TCHAR* buff = get_string_chars(env, text);

	SendMessage(hwnd, EM_SETSEL, (WPARAM) pos, (WPARAM) pos);
	SendMessage(hwnd, EM_REPLACESEL, (WPARAM) TRUE, (LPARAM) buff);
	
	free(buff);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextAreaPeer
 * Method:    getNativePreferredSize
 * Signature: (III)Ljava/awt/Dimension;
 */
JNIEXPORT jobject JNICALL Java_gnu_java_awt_peer_wce_WCETextAreaPeer_getNativePreferredSize(JNIEnv *env, jobject peer_obj, jint windowHandle, jint rows, int cols) {
	jclass clazz;
	jmethodID constructor_id;
	jobject dim;
	int cx, cy, width, height;
	SIZE size;

	get_text_extent_point((HWND) windowHandle, _T("A"), &size);

	// 行数が0の場合
	if (rows == 0) {
		rows = DEFAULT_ROWS;
	}

	// 列数が0の場合
	if (cols == 0) {
		cols = DEFAULT_COLS;
	}

	// システム情報を取得する
	cx = GetSystemMetrics(SM_CXBORDER);
	cy = GetSystemMetrics(SM_CYBORDER);
	
	width = size.cx * cols + cx * 2;
	height = (int) (size.cy * 1.1 * rows + cy * 2);

	clazz = (*env)->FindClass(env, "java/awt/Dimension");
	constructor_id = (*env)->GetMethodID(env, clazz, "<init>", "(II)V");

	dim = (*env)->NewObject(env,
							clazz,
							constructor_id,
							width,
							height);
	return dim;
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextAreaPeer
 * Method:    replaceNativeRange
 * Signature: (ILjava/lang/String;II)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCETextAreaPeer_replaceNativeRange(JNIEnv *env, jobject peer_obj, jint windowHandle, jstring text, jint startPos, jint endPos) {
	HWND hwnd = (HWND) windowHandle;
	_TCHAR* buff = get_string_chars(env, text);

	SendMessage(hwnd, EM_SETSEL, (WPARAM) startPos, (WPARAM) endPos);
	SendMessage(hwnd, EM_REPLACESEL, (WPARAM) TRUE, (LPARAM) buff);
	
	free(buff);
}
