/*===============================================================================================
 Native C code for accessing FMOD libraries.
 peter "pdx" drescher
 www.twittering.com

===============================================================================================*/

#include <jni.h>
#include <android/log.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "../../fmodexapi/fmodeventapi/api/inc/fmod_event.h"
#include "../../fmodexapi/api/inc/fmod_errors.h"

FMOD_SYSTEM  *gSystem  = 0;
FMOD_EVENTSYSTEM *gEventSystem  = 0;
FMOD_MUSICSYSTEM *gMusicSystem  = 0;

#define CHECK_RESULT(x) \
{ \
	FMOD_RESULT _result = x; \
	if (_result != FMOD_OK) \
	{ \
		__android_log_print(ANDROID_LOG_ERROR, "fmod", "FMOD error! (%d) %s\n%s:%d", _result, FMOD_ErrorString(_result), __FILE__, __LINE__); \
		exit(-1); \
	} \
}

void Java_com_twittering_landseaair_FMODaudio_cInitFMOD(JNIEnv *env, jobject thiz)
{
	FMOD_RESULT result = FMOD_OK;
	srand (time(NULL));

	//__android_log_print(ANDROID_LOG_ERROR, "fmod", "create event system INIT AUDIO SYSTEM");
	result = FMOD_EventSystem_Create(&gEventSystem);
	CHECK_RESULT(result);

	//__android_log_print(ANDROID_LOG_ERROR, "fmod", "init event system");
	result = FMOD_EventSystem_Init(gEventSystem, 32, FMOD_INIT_NORMAL, 0, FMOD_EVENT_INIT_NORMAL);
	CHECK_RESULT(result);

	//__android_log_print(ANDROID_LOG_ERROR, "fmod", "get musicsystem");
	result = FMOD_EventSystem_GetMusicSystem(gEventSystem, &gMusicSystem);
	CHECK_RESULT(result);
}

FMOD_EVENTSYSTEM *getEventSystem() {
	return (gEventSystem);
}

FMOD_MUSICSYSTEM *getMusicSystem() {
	return (gMusicSystem);
}

void Java_com_twittering_landseaair_FMODaudio_cUpdate(JNIEnv *env, jobject thiz)
{
	FMOD_RESULT	result = FMOD_OK;
	//called every 75ms by FMODaudio.java
	result = FMOD_EventSystem_Update(gEventSystem);
	CHECK_RESULT(result);
	AirUpdate();
}

void Java_com_twittering_landseaair_FMODaudio_cReleaseFMOD(JNIEnv *env, jobject thiz)
{
	FMOD_RESULT result = FMOD_OK;
	result = FMOD_EventSystem_Release(gEventSystem);
	CHECK_RESULT(result);
}

