/* 
 * JNI utility functions, from the book "The Java Native Interface" by
 * Sheng Liang.
 */

#include "jg_jnu.h"
#include <stddef.h>
#include <gtk/gtk.h>

#ifdef __cplusplus
extern "C" {
#endif

static JavaVM *cached_jvm;

/** From "The Java Native Interface", section 8.4.1 */
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved)
{
    cached_jvm = jvm;
    return JNI_VERSION_1_2;
}

/** From "The Java Native Interface", section 8.4.1 */
JNIEnv *JNU_GetEnv()
{
    JNIEnv *env;
    (*cached_jvm)->GetEnv(cached_jvm, (void **)&env, JNI_VERSION_1_2);
    return env;
}

/** From "The Java Native Interface", section 6.1.2 */
void JNU_ThrowByName(JNIEnv *env, const char *name, const char *msg)
{
    jclass cls = (*env)->FindClass(env, name);
    /* if cls is NULL, an exception has already been thrown */
    if (cls != NULL)
	(*env)->ThrowNew(env, cls, msg);
    /* free the local ref */
    (*env)->DeleteLocalRef(env, cls);
}

gchar** getStringArray(JNIEnv *env, jobjectArray anArray) 
{
	jsize len = (*env)->GetArrayLength(env, anArray);
	gchar **strArray = g_malloc0((len+1) * sizeof(gchar*));
	int index;
	
	for (index = 0; index < len; index++) {
		jstring aString = (jstring)(*env)->GetObjectArrayElement(env, anArray, (jsize)index);
		strArray[index] = (gchar*)(*env)->GetStringUTFChars(env, aString, NULL);
	}
	strArray[len] = NULL;
	
	return strArray;
}

void freeStringArray(JNIEnv *env, jobjectArray anArray, gchar** str)
{
	jsize len = (*env)->GetArrayLength(env, anArray);
	int index;
	for (index = 0; index < len; index++) {
		jstring aString = (jstring)(*env)->GetObjectArrayElement(env, anArray, (jsize)index);
		(*env)->ReleaseStringUTFChars(env, aString, str[index]);
	}
}

jobject getList(JNIEnv *env, GSList* list)
{
	// MUSTDO: need to implement this method.
	return NULL;
}

GSList* setList(JNIEnv *env, jobject list)
{
	// MUSTDO:  need to implement this method
	return NULL;
}

#ifdef __cplusplus
}
#endif
