#include <stdlib.h>
#include <stdio.h>
#include <jni.h>

typedef int bool;
#define true 1
#define false 0

static void fatal(JNIEnv* env, char* str)
{
	fputs(str, stderr);
	fputc('\n', stderr);
	fflush(stderr);
	if((*env)->ExceptionCheck(env))
		(*env)->ExceptionDescribe(env);
	fflush(stderr);
	exit(1);
}

static bool initJavaLogger(JNIEnv* env)
{
	jclass logHandlerClass = (*env)->FindClass(env, "se/tada/tests/LogHandler");
	if(logHandlerClass == 0)
		fatal(env, "Unable to find class se.tada.tests.LogHandler");

	jmethodID init = (*env)->GetStaticMethodID(env, logHandlerClass, "init", "()V");
	if(init == 0)
		fatal(env, "Unable to find method se.tada.tests.LogHandler.init()");

	fputs("Now calling LogHandler.init()\n", stderr);
	fflush(stderr);

	(*env)->CallStaticVoidMethod(env, logHandlerClass, init);
	(*env)->DeleteLocalRef(env, logHandlerClass);
	if((*env)->ExceptionCheck(env))
	{
		(*env)->ExceptionDescribe(env);
		return false;
	}
	return true;
}

static bool useJavaLogger(JNIEnv* env)
{
	jclass logUserClass = (*env)->FindClass(env, "se/tada/tests/LogUser");
	if(logUserClass == 0)
		fatal(env, "Unable to find class se.tada.tests.LogUser");

	jmethodID hello = (*env)->GetStaticMethodID(env, logUserClass, "hello", "()V");
	if(hello == 0)
		fatal(env, "Unable to find method se.tada.tests.LogUser.hello()");

	fputs("Now calling LogUser.init()\n", stderr);
	fflush(stderr);

	(*env)->CallStaticVoidMethod(env, logUserClass, hello);
	(*env)->DeleteLocalRef(env, logUserClass);
	if((*env)->ExceptionCheck(env))
	{
		(*env)->ExceptionDescribe(env);
		return false;
	}
	return true;
}

int main(int argc, char** argv)
{
	JavaVM* javaVM = 0;
	JNIEnv* env    = 0;
	JavaVMInitArgs vm_args;

	vm_args.nOptions = 0;
	vm_args.options  = 0;
	vm_args.version  = JNI_VERSION_1_4;
	vm_args.ignoreUnrecognized = JNI_FALSE;

	if(JNI_CreateJavaVM(&javaVM, (void**)&env, &vm_args) != JNI_OK)
	{
		fputs("Unable to create Java VM\n", stderr);
		return 1;
	}

	return (initJavaLogger(env) && useJavaLogger(env)) ? 0 : 1;
}
