/*
 * ScsiAdr.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_ScsiAdr.h"
#include "BindingsUtil.h"

#include "libburn.h"


/*
 * Class:     org_pykix_libburnia_libburn_ScsiAdr
 * Method:    burn_drive_convert_scsi_adr
 * Signature: (IIIII)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL 
Java_org_pykix_libburnia_libburn_ScsiAdr_burn_1drive_1convert_1scsi_1adr
(
	JNIEnv *env, jclass cls, jint bus_no, jint host_no, jint channel_no,
	jint target_no, jint lun_no
)
{
	char adr[BURN_DRIVE_ADR_LEN];

	if ( burn_drive_convert_scsi_adr(bus_no, host_no, channel_no,
				 target_no, lun_no, adr) != 1 ) {
		java_libburn_throw_burn_exception(env, "Can't convert SCSI adr");
		return NULL;
	}
	return (*env)->NewStringUTF(env, adr);
}

/*
 * Class:     org_pykix_libburnia_libburn_ScsiAdr
 * Method:    burn_drive_obtain_scsi_adr
 * Signature: (Ljava/lang/String;)Lorg/pykix/libburnia/libburn/ScsiAdr;
 */
JNIEXPORT jobject JNICALL 
Java_org_pykix_libburnia_libburn_ScsiAdr_burn_1drive_1obtain_1scsi_1adr
(
	JNIEnv *env, jclass cls, jstring path
)
{
	const char* cpath;
	int bus_no;
	int host_no;
	int channel_no;
	int target_no; 
	int lun_no;
	static jclass scsiAdrCls = NULL;
	static jmethodID cid = NULL;
	
	cpath = (*env)->GetStringUTFChars(env, path, NULL);
	if ( cpath == NULL ) {
		return NULL; /* OutOfMemoryError already thrown */
	}

	if ( burn_drive_obtain_scsi_adr( (char *) path, &bus_no, &host_no,
				&channel_no, &target_no, &lun_no) != 1 ) {
		(*env)->ReleaseStringUTFChars(env, path, cpath);
		java_libburn_throw_burn_exception(env, "Can't convert SCSI adr");
		return NULL;
	}

	(*env)->ReleaseStringUTFChars(env, path, cpath);

	if ( scsiAdrCls == NULL ) {
		scsiAdrCls = java_libburn_find_class(env, "org/pykix/libburnia/libburn/ScsiAdr");
		if ( scsiAdrCls == NULL ) {
			return NULL;
		}
	}

	if ( cid == NULL ) {
		cid = (*env)->GetMethodID(env, scsiAdrCls, "<init>", "(IIIII)V");
		if (cid == NULL) {
		    return NULL; /* exception thrown */
		}
	}

	return (*env)->NewObject(env, scsiAdrCls, cid, bus_no, host_no,
				channel_no, target_no, lun_no);
}
