//
// Created by Ht on 2021/1/12.
//

#ifndef LIBDEVCPP_QJEDGEJNISERVICEUTIL_H
#define LIBDEVCPP_QJEDGEJNISERVICEUTIL_H


#ifdef ANDROID

#include <jni.h>
#include <string>
#include <qlibc/QJNIUtil.h>
#include <qlibc/QLogger.h>

#define JedgeGlobalVar() glServer

#define JedgeImplServiceApi(pkg,server_type,service_name) \
\
server_type* glServer = nullptr; \
implJni(pkg, jstring, getServiceName)(\
    JNIEnv* env,\
    jobject /* this */) { \
    return env->NewStringUTF(service_name);\
}\
\
implJni(pkg, jboolean, startService)(\
    JNIEnv* env,\
    jobject /* this */, jobject initData) {\
    QLog("Starting %s ...", service_name);\
    if(glServer!=nullptr){\
        return false;\
    }\
    qlibc::QData d;\
    qlibc::QJNIUtil::CppQDataFromJavaQData(env, d, initData);\
    glServer = new server_type(d); \
    if(!glServer->start(d)){\
        delete glServer;\
        glServer = nullptr;\
        QLog("Failed.");\
        return false;\
    }\
    QLog("Ok.");\
    return true;\
}\
\
implJni(pkg, void, shutdownService) (\
    JNIEnv* env,\
    jobject /* this */) {\
    if(glServer!=nullptr){\
        if(glServer->isRunning()){\
            glServer->shutdown();\
        }\
        delete glServer;\
        glServer = nullptr;\
        QLog("Service shutdown.");\
    }\
}\
\
implJni(pkg, jboolean, isRunning) (\
    JNIEnv* env,\
    jobject /* this */) {\
    return glServer!= nullptr && glServer->isRunning();\
}\

#endif //ANDROID

#endif //LIBDEVCPP_QJEDGEJNISERVICEUTIL_H
