/*
 * SPDX-FileCopyrightText: Sebastiano Barezzi
 * SPDX-License-Identifier: Apache-2.0
 */

#pragma once

#include <functional>
#include <jni.h>
#include <stdexcept> // For std::runtime_error

// Helper for stringifying preprocessor macros
#define STRINGIFY_IMPL(x) #x
#define STRINGIFY(x) STRINGIFY_IMPL(x)

#define JNI_CHECK(env) \
    if (env->ExceptionCheck()) { \
        env->ExceptionDescribe(); \
        env->ExceptionClear(); \
        throw std::runtime_error("JNI exception at " __FILE__ ":" STRINGIFY(__LINE__)); \
    }

void withJniCheck(JNIEnv *env, const std::function<void()> &func);

template<typename T>
T withJniCheck(JNIEnv *env, const std::function<T()> &func) {
    T result = func();

    if (env->ExceptionCheck()) {
        env->ExceptionDescribe();
        env->ExceptionClear();
        throw std::runtime_error("JNI exception");
    }

    return result;
}

jmethodID getArrayListAddMethodID(JNIEnv *env, jobject object);

#define STRING_CLASS_SIG "Ljava/lang/String;"
