//
// Created by 阳坤 on 2022/2/23.
//

#include "ImageBlurDetection.h"


static jint Java_JNI_OpenCV_ImagePathBlurDetection(JNIEnv *env, jobject obj, jstring filepath) {
    const char *image_path = env->GetStringUTFChars(filepath, 0);
    int ret = image_blur_detection(image_path);
    env->ReleaseStringUTFChars(filepath, image_path);
    return ret;
}

static jstring Java_JNI_OpenCV_GetVideoSimilarityLists(JNIEnv *env, jobject obj, jstring filepath) {
    LOGE("Java_JNI_OpenCV_GetVideoSimilarityLists\n ");
    const char *image_path = env->GetStringUTFChars(filepath, 0);
    const char *ret_json = get_video_similarity_list(image_path);
    env->ReleaseStringUTFChars(filepath, image_path);
    LOGE("Java_JNI_OpenCV_GetVideoSimilarityLists\n");
    if (ret_json) {
        LOGE("Java_JNI_OpenCV_GetVideoSimilarityLists NewStringUTF \n");
        jstring str = env->NewStringUTF(ret_json);
        LOGE("Java_JNI_OpenCV_GetVideoSimilarityLists NewStringUTF 1\n");
        free((void *) ret_json);
        LOGE("Java_JNI_OpenCV_GetVideoSimilarityLists NewStringUTF out\n");
        ret_json = NULL;
        return str;
    }
    return NULL;
}

static jint
Java_JNI_OpenCV_ImageBytesBlurDetection(JNIEnv *env, jobject obj, jbyteArray data) {
    jbyte *image_bytes = env->GetByteArrayElements(data, 0);
    int ret = bytes_blur_detection((uint8_t *) image_bytes, env->GetArrayLength(data));
    env->ReleaseByteArrayElements(data, image_bytes, 0);
    return ret;
}


static const JNINativeMethod configMethods[] = {
        {"blurDetectionFromImagePath",  "(Ljava/lang/String;)I",                 (void **) Java_JNI_OpenCV_ImagePathBlurDetection},
        {"blurDetectionFromImageBytes", "([B)I",                                 (void **) Java_JNI_OpenCV_ImageBytesBlurDetection},
        {"getVideoSimilarityLists",     "(Ljava/lang/String;)Ljava/lang/String;", (void **) Java_JNI_OpenCV_GetVideoSimilarityLists},
};


/**
 *  System.load(xxx.so) ִ
 * @param vm
 * @param pVoid
 * @return
 */
int JNI_OnLoad(JavaVM *vm, void *pVoid) {
    JNIEnv *jniEnv;
    if (vm->GetEnv(reinterpret_cast<void **>(&jniEnv), JNI_VERSION_1_6) != JNI_OK) {
        printf(" JNI_OnLoad  1 error.\n");
        return JNI_ERR;
    }
    jclass jcls = jniEnv->FindClass(JAVA_JNI_CLASS_PATH);
    if (jniEnv->RegisterNatives(jcls, configMethods, NELEM(configMethods)) != JNI_OK) {
        printf(" JNI_OnLoad  error.\n");
        return JNI_ERR;
    }
    printf(" JNI_OnLoad  ok.\n");
    return JNI_VERSION_1_6;
};