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

/*
 * Class:     gnu_java_awt_peer_wce_WCETextComponentPeer
 * Method:    getNativeSelectionEnd
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_WCETextComponentPeer_getNativeSelectionEnd(JNIEnv *env, jobject peer_obj, jint windowHandle) {
	HWND hwnd = (HWND) windowHandle;
	DWORD end;
	SendMessage(hwnd, EM_GETSEL, 0, (LPARAM) &end);
	return (jint) end;
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextComponentPeer
 * Method:    getNativeSelectionStart
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_WCETextComponentPeer_getNativeSelectionStart(JNIEnv *env, jobject peer_obj, jint windowHandle) {
	HWND hwnd = (HWND) windowHandle;
	DWORD start;
	SendMessage(hwnd, EM_GETSEL, (WPARAM) &start, 0);
	return (jint) start;
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextComponentPeer
 * Method:    selectNative
 * Signature: (III)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCETextComponentPeer_selectNative(JNIEnv *env, jobject peer_obj, jint windowHandle, jint startPos, jint endPos) {
	SendMessage((HWND) windowHandle, EM_SETSEL, (WPARAM) startPos, (LPARAM) endPos);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextComponentPeer
 * Method:    setNativeEditable
 * Signature: (IZ)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCETextComponentPeer_setNativeEditable(JNIEnv *env, jobject peer_obj, jint windowHandle, jboolean editable) {
	SendMessage((HWND) windowHandle, EM_SETREADONLY, (WPARAM) (editable ? FALSE : TRUE), 0);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextComponentPeer
 * Method:    getNativeCaretPosition
 * Signature: (I)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_WCETextComponentPeer_getNativeCaretPosition(JNIEnv *env, jobject peer_obj, jint windowHandle) {
	DWORD start;
	SendMessage((HWND) windowHandle, EM_GETSEL, (WPARAM) &start, 0);
	return (jint) start;
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextComponentPeer
 * Method:    setNativeCaretPosition
 * Signature: (II)V
 */
JNIEXPORT void JNICALL Java_gnu_java_awt_peer_wce_WCETextComponentPeer_setNativeCaretPosition(JNIEnv *env, jobject peer_obj, jint windowHandle, jint pos) {
	SendMessage((HWND) windowHandle, EM_SETSEL, (WPARAM) pos, (WPARAM) pos);
}

/*
 * Class:     gnu_java_awt_peer_wce_WCETextComponentPeer
 * Method:    getNativeIndexAtPoint
 * Signature: (III)I
 */
JNIEXPORT jint JNICALL Java_gnu_java_awt_peer_wce_WCETextComponentPeer_getNativeIndexAtPoint(JNIEnv *env, jobject peer_obj, jint windowHandle, jint x, jint y) {
	return LOWORD(SendMessage((HWND) windowHandle, EM_CHARFROMPOS, 0, MAKELPARAM(x, y)));
}