/*
 * Message.c
 *
 * Copyright (c) 2007  Vreixo Formoso
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * See COPYING file for details.
 */

#include "org_pykix_libburnia_libburn_Message.h"

#include "libburn.h"


/*
 * Class:     org_pykix_libburnia_libburn_Message
 * Method:    burn_msgs_set_severities
 * Signature: (Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I
 */
JNIEXPORT jint JNICALL 
Java_org_pykix_libburnia_libburn_Message_burn_1msgs_1set_1severities
(
	JNIEnv *env, jclass cls, jstring queueSev, jstring printSev, jstring printId
)
{
	int res;
	const char *queue_severity;
	const char *print_severity;
	const char *print_id;

	queue_severity = (*env)->GetStringUTFChars(env, queueSev, NULL);
	if ( queue_severity == NULL ) {
		return -1; /* OutOfMemoryError already thrown */
	}

	print_severity = (*env)->GetStringUTFChars(env, printSev, NULL);
	if ( print_severity == NULL ) {
		return -1; /* OutOfMemoryError already thrown */
	}

	print_id = (*env)->GetStringUTFChars(env, printId, NULL);
	if ( print_id == NULL ) {
		return -1; /* OutOfMemoryError already thrown */
	}
	

	res = burn_msgs_set_severities( (char *) queue_severity, 
		(char *) print_severity, (char *) print_id);

	(*env)->ReleaseStringUTFChars(env, queueSev, queue_severity);
	(*env)->ReleaseStringUTFChars(env, printSev, print_severity);
	(*env)->ReleaseStringUTFChars(env, printId, print_id);

	return res;
}

/*
 * Class:     org_pykix_libburnia_libburn_Message
 * Method:    burn_msgs_obtain
 * Signature: (Ljava/lang/String;)Lorg/pykix/libburnia/libburn/Message;
 */
JNIEXPORT jobject JNICALL 
Java_org_pykix_libburnia_libburn_Message_burn_1msgs_1obtain
(
	JNIEnv *env, jclass cls, jstring minSev
)
{
	
	const char *minimum_severity;
	int error_code;
	int os_errno;
	char msg_text[BURN_MSGS_MESSAGE_LEN];
	char severity[80];
	static jmethodID cid = NULL;

	minimum_severity = (*env)->GetStringUTFChars(env, minSev, NULL);
	if ( minimum_severity == NULL ) {
		return NULL; /* OutOfMemoryError already thrown */
	}

	if ( cid == NULL ) {
		cid = (*env)->GetMethodID(env, cls, "<init>", "(ILjava/lang/String;ILjava/lang/String;)V");
		if (cid == NULL) {
		    return NULL; /* exception thrown */
		}
	}

	int res = burn_msgs_obtain( (char *) minimum_severity, &error_code, msg_text, 
					&os_errno, severity);

	jobject message = NULL;
	if ( res == 1 ) {
		
		jstring msgText = (*env)->NewStringUTF(env, msg_text);
		jstring sev = (*env)->NewStringUTF(env, severity);

		message = (*env)->NewObject(env, cls, cid, error_code, msgText, os_errno, sev);

		(*env)->DeleteLocalRef(env, msgText);
		(*env)->DeleteLocalRef(env, sev);
	}

	(*env)->ReleaseStringUTFChars(env, minSev, minimum_severity);
	
	return message;
}


