// For native drawing
#include <ui/SurfaceComposerClient.h>
android::Surface *g_pSurface;
 
 
JNIEXPORT jboolean JNICALL Java_our_shit_here_SetSurface
(JNIEnv *env, jclass cls, jobject surfaceObject, jint width, jint height)
{
  jclass jsurface = env->FindClass("android/view/Surface");
  if (jsurface == NULL)
    return false;
  jfieldID Surface_nativeInstanceID = env->GetFieldID(jsurface, "mSurface", "I");
 
  g_pSurface = (android::Surface*)env->GetIntField(surfaceObject, Surface_nativeInstanceID);
  if ( g_pSurface ) {
    // g_andSurface = android::sp<android::Surface>(p);
    g_sp_andSurface = g_pSurface->dup();
    g_bDrawSurface = true;
    if(info.m_width != width || info.m_height != height) {
      Java_our_shit_here_sizeChanged(env, cls, width, height, true);
    } else if (g_pFrame != NULL) {
      unsigned int arraySize = g_iFrameWidth * g_iFrameHeight;
      g_ourShit.FlipToScreen(g_pFrame, arraySize, g_iFrameWidth, g_iFrameHeight);
      g_pFrame = NULL;
      g_iFrameWidth = 0;
      g_iFrameHeight = 0;
    }
    return true;
  } else {
    return false;
  }
}
 
static unsigned char* g_pFrame = NULL;
static int g_iFrameWidth = 0;
static int g_iFrameHeight = 0;
 
 
void OurShit::FlipToScreen(unsigned char* pixelPtr, unsigned int arraySize, int width, int height)
{
  if(!g_bDrawSurface) {
    g_pFrame = pixelPtr;
    g_iFrameWidth = width;
    g_iFrameHeight = height;
    return;
  }
  // It is possible that we have been informed of a resolution change, but we have not yet had a chance to change resolutions.
  if(info.m_width != width || info.m_height != height)
    return;
 
  if(NULL != g_pSurface) {
    android::Surface::SurfaceInfo surfaceinfo;
    g_pSurface->lock(&surfaceinfo);
    // Double check our resolution! If we shouldn't draw anything, send through a black canvas.
    if(width == surfaceinfo.w && height == surfaceinfo.h)
      memcpy(surfaceinfo.bits, pixelPtr, 2 * arraySize); // RGB565 16bits
    else
      memset(surfaceinfo.bits, 0, 2 * arraySize);
    g_pSurface->unlockAndPost();
#ifdef ANDROIDAPP_LOGGING
  } else {
    LogMessage("Can not get surface");
#endif
  }
}
