#include "TerminalDevice.h"
#include <dlfcn.h>
#include "Camera.h"
#include <AndroidHelper.h>

typedef jbyteArray (*TakePhotoFunc)(int, int, int, int);

extern bool GetJniEnv(JavaVM *vm, JNIEnv **env, bool& didAttachThread);

CTerminalDevice::CTerminalDevice(JavaVM* vm, jobject service)
{
    m_vm = vm;
    JNIEnv* env = NULL;
    bool attached = false;
    bool res = GetJniEnv(m_vm, &env, attached);
    if (!res)
    {
        ALOGE("Failed to get JNI Env");
    }
    m_javaService = env->NewGlobalRef(service);
    if (attached)
    {
        vm->DetachCurrentThread();
    }
}

CTerminalDevice::~CTerminalDevice()
{
    JNIEnv* env = NULL;
    bool attached = false;
    bool res = GetJniEnv(m_vm, &env, attached);
    if (!res)
    {
        ALOGE("Failed to get JNI Env");
    }
    env->DeleteGlobalRef(m_javaService);
    if (attached)
    {
        m_vm->DetachCurrentThread();
    }
    m_javaService = NULL;
}

bool CTerminalDevice::TakePhoto(unsigned char channel, unsigned char preset, const string& path, bool photo)
{
    jboolean res = JNI_FALSE;

    CCamera camera;
    camera.initCamera(NULL);
    if (camera.isCameraReady())
    {
        camera.takePicture();
    }

    camera.closeCamera();

#if 0
    JNIEnv* env = NULL;
    bool attached = GetJniEnv(m_vm, &env);
    jclass serviceClass = env->GetObjectClass(m_javaService);
    jmethodID mid = env->GetMethodID(serviceClass, "takePhoto", "(SSLjava/lang/String;)Z");
    jstring str = env->NewStringUTF(path.c_str());
    res = env->CallBooleanMethod (m_javaService, mid, (jint)channel, (jint)preset, str);
    env->ReleaseStringUTFChars(str, path.c_str());
    env->DeleteLocalRef(serviceClass);

    if (!res)
    {
        int aa = 1;
    }
    if (attached)
    {
        m_vm->DetachCurrentThread();
    }
#endif

	return res == JNI_TRUE;
}

