/*  Given a local index, return (initialized if needed) a rec containing the
    encoded data and length. The bitmap field is initialized to 0, and is not
    filled in by this routine per-se.
 */
static EncodeDataRec* get_encoderec(int index) {
    if ((unsigned)index >= GMOJI_PUA_COUNT) {
        SkDebugf("bad index passed to EncodeDataRec& get_encode_data %d\n",
                 index);
        return NULL;
    }

    // lazily fill in the data
    EncodeDataRec* rec = &gGmojiEncodeData[index];

    if (NOT_AVAILABLE_ENCODE_SIZE == rec->fSize) {
        return NULL;
    }
    if (UNINITIALIZED_ENCODE_SIZE == rec->fSize) {
        EmojiFactory* fact = get_emoji_factory();
        if (NULL == fact) {
            return NULL;
        }

        int32_t pua = GMOJI_PUA_MIN + gGmojiPUA[index];
        rec->fData = fact->GetImageBinaryFromAndroidPua(pua, &rec->fSize);
        if (NULL == rec->fData) {
            // flag this entry is not available, so we won't ask again
            rec->fSize = NOT_AVAILABLE_ENCODE_SIZE;
            return NULL;
        }
    }
    return rec;
}
static jobject android_emoji_EmojiFactory_getBitmapFromAndroidPua(
    JNIEnv* env, jobject clazz, jlong nativeEmojiFactory, jint pua) {
  EmojiFactory *factory = reinterpret_cast<EmojiFactory *>(nativeEmojiFactory);

  int size;
  const char *bytes = factory->GetImageBinaryFromAndroidPua(pua, &size);
  if (bytes == NULL) {
    return NULL;
  }

  SkBitmap *bitmap = new SkBitmap;
  if (!SkImageDecoder::DecodeMemory(bytes, size, bitmap)) {
    ALOGE("SkImageDecoder::DecodeMemory() failed.");
    return NULL;
  }

  return GraphicsJNI::createBitmap(env, bitmap,
      GraphicsJNI::kBitmapCreateFlag_Premultiplied, NULL);
}
static jobject android_emoji_EmojiFactory_getBitmapFromAndroidPua(
    JNIEnv* env, jobject clazz, jint nativeEmojiFactory, jint pua) {
  EmojiFactory *factory = reinterpret_cast<EmojiFactory *>(nativeEmojiFactory);

  int size;
  const char *bytes = factory->GetImageBinaryFromAndroidPua(pua, &size);
  if (bytes == NULL) {
    return NULL;
  }

  SkBitmap *bitmap = new SkBitmap;
  if (!SkImageDecoder::DecodeMemory(bytes, size, bitmap)) {
    LOGE("SkImageDecoder::DecodeMemory() failed.");
    return NULL;
  }

  jobject obj = env->NewObject(gBitmap_class, gBitmap_constructorMethodID,
      static_cast<jint>(reinterpret_cast<uintptr_t>(bitmap)), NULL, false, NULL, -1);
  if (env->ExceptionCheck() != 0) {
    LOGE("*** Uncaught exception returned from Java call!\n");
    env->ExceptionDescribe();
  }
  return obj;
}