/*
 *  Copyright (C) 2004-2025 Savoir-faire Linux Inc.
 *
 *  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, see <https://www.gnu.org/licenses/>.
 */

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

JavaVM *gJavaVM;
const char *kjamiservicePath = "net/jami/daemon/JamiServiceJNI";

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 (kjamiservicePath);
	if (!clazz) {
        JAMI_ERR("JNI_Onload: whoops, %s class not found!", kjamiservicePath);
	}
	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(kjamiservicePath);
	if (!clazz) {
        JAMI_ERR("JNI_OnUnLoad: whoops, %s class not found!", kjamiservicePath);
	}

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

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