/*
 *  Copyright (C) 2004-2021 Savoir-faire Linux Inc.
 *
 *  Author: Emeric Vigier <emeric.vigier@savoirfairelinux.com>
 *
 *  This program 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 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include "logger.h"
extern "C" {
#include "libavcodec/jni.h"
}

JavaVM *gJavaVM;
const char *kringservicePath = "cx/ring/daemon/RingserviceJNI";

void deinitClassHelper(JNIEnv *env, jobject obj) {
	JAMI_INFO("deinitClassHelper");

	/* delete cached object instances */
    env->DeleteGlobalRef(obj);
	JAMI_INFO("deinitClassHelper: object %p deleted", obj);
}

JNIEXPORT jint JNI_OnLoad(JavaVM *vm, void *reserved) {
	JNIEnv *env;
	jclass clazz;
	jint r;

    JAMI_INFO("JNI_OnLoad");

	if (av_jni_set_java_vm(vm, reserved)) {
        JAMI_ERR("JNI_OnLoad: av_jni_set_java_vm failed");
	}

	//Assume it is c++
	r = vm->GetEnv ((void **) &env, JNI_VERSION_1_6);
    if (r != JNI_OK) {
		JAMI_ERR("JNI_OnLoad: failed to get the environment using GetEnv()");
        return -1;
    }
	JAMI_INFO("JNI_Onload: GetEnv %p", env);

	clazz = env->FindClass (kringservicePath);
	if (!clazz) {
        JAMI_ERR("JNI_Onload: whoops, %s class not found!", kringservicePath);
	}
	gJavaVM = vm;
	JAMI_INFO("JNI_Onload: JavaVM %p", gJavaVM);

	/* put instances of class object we need into cache */
    //initClassHelper(env, kManagerPath, &gManagerObject);

	JNINativeMethod methods[] = {

	$defs

	};

	r = env->RegisterNatives (clazz, methods, (int) (sizeof(methods) / sizeof(methods[0])));
	return JNI_VERSION_1_6;
}

void JNI_OnUnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
	jclass clazz;

	JAMI_INFO("JNI_OnUnLoad");

	/* get env */
    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
		JAMI_ERR("JNI_OnUnLoad: failed to get the environment using GetEnv()");
        return;
    }
	JAMI_INFO("JNI_OnUnLoad: GetEnv %p", env);

    /* Get jclass with env->FindClass */
	clazz = env->FindClass(kringservicePath);
	if (!clazz) {
        JAMI_ERR("JNI_OnUnLoad: whoops, %s class not found!", kringservicePath);
	}

	/* remove instances of class object we need into cache */
    //deinitClassHelper(env, gManagerObject);

	env->UnregisterNatives(clazz);
	JAMI_INFO("JNI_OnUnLoad: Native functions unregistered");
}
