/*  RetroArch - A frontend for libretro.
 *  Copyright (C) 2010-2014 - Hans-Kristian Arntzen
 *  Copyright (C) 2011-2017 - Daniel De Matteis
 *  Copyright (C) 2012-2015 - Michael Lelli
 *  Copyright (C) 2013-2014 - Steven Crowe
 *
 *  RetroArch is free software: you can redistribute it and/or modify it under the terms *  of the GNU General Public License as published by the Free Software Found-
 *  ation, either version 3 of the License, or (at your option) any later version.
 *
 *  RetroArch is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 *  PURPOSE.  See the GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along with RetroArch.
 *  If not, see <http://www.gnu.org/licenses/>.
 */

#include "../../config.def.h"

#include "../input_driver.h"
#include "../../frontend/drivers/platform_unix.h"
#include "../drivers_keyboard/keyboard_event_android.h"

static const char *android_joypad_name(unsigned pad)
{
   return input_config_get_device_name(pad);
}

JNIEXPORT void JNICALL
Java_com_xugame_app_JoypadManager_addJoystickNative(
        JNIEnv *env, jclass clazz,
        jint id, jint source
) {
   struct android_app   *android_app = (struct android_app*)g_android;
   input_driver_state_t *input_st    = input_state_get_ptr();
   android_input_t      *android     = (android_input_t*)input_st->current_data;
   int                   port        = -1;

   char device_name[256];
   char name_buf[256];
   int vendorId                 = 0;
   int productId                = 0;
   const char *device_model     = android->device_model;

   if (android->pads_connected > MAX_USERS) {
      return;
   }

   device_name[0] = name_buf[0] = '\0';

   if (!engine_lookup_name(device_name, &vendorId,
                           &productId, sizeof(device_name), id))
      return;

   /* FIXME - per-device hacks for NVidia Shield, Xperia Play and
    * similar devices
    *
    * These hacks depend on autoconf, but can work with user
    * created autoconfs properly
    */

   /* NVIDIA Shield Console
    * This is the most complicated example, the built-in controller
    * has an extra button that can't be used and a remote.
    *
    * We map the remote for navigation and overwrite whenever a
    * real controller is connected.
    * Also group the NVIDIA button on the controller with the
    * main controller inputs so it's usable. It's mapped to
    * menu by default
    *
    * The NVIDIA button is identified as "Virtual" device when first
    * pressed. CEC remote input is also identified as "Virtual" device.
    * If a virtual device is detected before a controller then it will
    * be assigned to port 0 as "SHIELD Virtual Controller". When a real
    * controller is detected it will overwrite the virtual controller
    * and be grouped with the NVIDIA button of the virtual device.
    *
    */
   if (strstr(device_model, "SHIELD Android TV") && (
           strstr(device_name, "Virtual") ||
           strstr(device_name, "NVIDIA Corporation NVIDIA Controller v01.0")))
   {
      /* only use the hack if the device is one of the built-in devices */
      RARCH_LOG("Special Device Detected: %s\n", device_model);
      {
#if 0
         RARCH_LOG("- Pads Mapped: %d\n- Device Name: %s\n- IDS: %d, %d, %d",
               android->pads_connected, device_name, id, pad_id1, pad_id2);
#endif
         /* Remove the remote or virtual controller device if it is mapped */
         if (strstr(android->pad_states[0].name,"SHIELD Remote") ||
             strstr(android->pad_states[0].name,"SHIELD Virtual Controller"))
         {
            pad_id1 = -1;
            pad_id2 = -1;
            android->pads_connected = 0;
            port = 0;
            strlcpy(name_buf, device_name, sizeof(name_buf));
         }

         /* if the actual controller has not been mapped yet,
          * then configure Virtual device for now */
         if (strstr(device_name, "Virtual") && android->pads_connected==0)
            strlcpy (name_buf, "SHIELD Virtual Controller", sizeof(name_buf));
         else
            strlcpy (name_buf, "NVIDIA SHIELD Controller", sizeof(name_buf));

         /* apply the hack only for the first controller
          * store the id for later use
         */
         if (strstr(device_name, "NVIDIA Corporation NVIDIA Controller v01.0")
             && android->pads_connected==0)
            pad_id1 = id;
         else if (strstr(device_name, "Virtual") && pad_id1 != -1)
         {
            id = pad_id1;
            return;
         }
      }
   }

   else if (strstr(device_model, "SHIELD") && (
           strstr(device_name, "Virtual") || strstr(device_name, "gpio") ||
           strstr(device_name, "NVIDIA Corporation NVIDIA Controller v01.01") ||
           strstr(device_name, "NVIDIA Corporation NVIDIA Controller v01.02")))
   {
      /* only use the hack if the device is one of the built-in devices */
      RARCH_LOG("Special Device Detected: %s\n", device_model);
      {
         if ( pad_id1 < 0 )
            pad_id1 = id;
         else
            pad_id2 = id;

         if ( pad_id2 > 0)
            return;
         strlcpy (name_buf, "NVIDIA SHIELD Portable", sizeof(name_buf));
      }
   }

   else if (strstr(device_model, "SHIELD") && (
           strstr(device_name, "Virtual") || strstr(device_name, "gpio") ||
           strstr(device_name, "NVIDIA Corporation NVIDIA Controller v01.03")))
   {
      /* only use the hack if the device is one of the built-in devices */
      RARCH_LOG("Special Device Detected: %s\n", device_model);
      {
         if (strstr(device_name, "NVIDIA Corporation NVIDIA Controller v01.03")
             && android->pads_connected==0)
            pad_id1 = id;
         else if (strstr(device_name, "Virtual") || strstr(device_name, "gpio"))
         {
            id = pad_id1;
            return;
         }
         strlcpy (name_buf, "NVIDIA SHIELD Gamepad", sizeof(name_buf));
      }
   }

      /* Other ATV Devices
       * Add other common ATV devices that will follow the Android
       * Gaempad convention as "Android Gamepad"
       */
      /* to-do: add DS4 on Bravia ATV */
   else if (strstr(device_name, "NVIDIA"))
      strlcpy (name_buf, "Android Gamepad", sizeof(name_buf));

      /* GPD XD
       * This is a simple hack, basically groups the "back"
       * button with the rest of the gamepad
       */
   else if (strstr(device_model, "XD") && (
           strstr(device_name, "Virtual") || strstr(device_name, "rk29-keypad") ||
           strstr(device_name,"Playstation3") || strstr(device_name,"XBOX")))
   {
      /* only use the hack if the device is one of the built-in devices */
      RARCH_LOG("Special Device Detected: %s\n", device_model);
      {
         if ( pad_id1 < 0 )
            pad_id1 = id;
         else
            pad_id2 = id;

         if ( pad_id2 > 0)
            return;

         strlcpy (name_buf, "GPD XD", sizeof(name_buf));
         port = 0;
      }
   }

      /* XPERIA Play
       * This device is composed of two hid devices
       * We make it look like one device
       */
   else if (
           (
                   string_starts_with_size(device_model, "R800", STRLEN_CONST("R800")) ||
                   strstr(device_model, "Xperia Play") ||
                   strstr(device_model, "Play") ||
                   strstr(device_model, "SO-01D")
           ) || (
                   strstr(device_name, "keypad-game-zeus") ||
                   strstr(device_name, "keypad-zeus") ||
                   strstr(device_name, "Android Gamepad")
           )
           )
   {
      /* only use the hack if the device is one of the built-in devices */
      RARCH_LOG("Special Device Detected: %s\n", device_model);
      {
         if ( pad_id1 < 0 )
            pad_id1 = id;
         else
            pad_id2 = id;

         if ( pad_id2 > 0)
            return;

         strlcpy (name_buf, "XPERIA Play", sizeof(name_buf));
         port = 0;
      }
   }

      /* ARCHOS Gamepad
       * This device is composed of two hid devices
       * We make it look like one device
       */
   else if (strstr(device_model, "ARCHOS GAMEPAD") && (
           strstr(device_name, "joy_key") || strstr(device_name, "joystick")))
   {
      /* only use the hack if the device is one of the built-in devices */
      RARCH_LOG("ARCHOS GAMEPAD Detected: %s\n", device_model);
      {
         if ( pad_id1 < 0 )
            pad_id1 = id;
         else
            pad_id2 = id;

         if ( pad_id2 > 0)
            return;

         strlcpy (name_buf, "ARCHOS GamePad", sizeof(name_buf));
         port = 0;
      }
   }

      /* Amazon Fire TV & Fire stick */
   else if (
           string_starts_with_size(device_model, "AFT", STRLEN_CONST("AFT")) &&
           (
                   strstr(device_model, "AFTB") ||
                   strstr(device_model, "AFTT") ||
                   strstr(device_model, "AFTS") ||
                   strstr(device_model, "AFTM") ||
                   strstr(device_model, "AFTRS")
           )
           )
   {
      RARCH_LOG("Special Device Detected: %s\n", device_model);
      {
         /* always map remote to port #0 */
         if (strstr(device_name, "Amazon Fire TV Remote"))
         {
            android->pads_connected = 0;
            port = 0;
            strlcpy(name_buf, device_name, sizeof(name_buf));
         }
            /* remove the remote when a gamepad enters */
         else if (strstr(android->pad_states[0].name,"Amazon Fire TV Remote"))
         {
            android->pads_connected = 0;
            port = 0;
            strlcpy(name_buf, device_name, sizeof(name_buf));
         }
         else
            strlcpy(name_buf, device_name, sizeof(name_buf));
      }
   }

      /* Other uncommon devices
       * These are mostly remote control type devices, bind them always to port 0
       * And overwrite the binding whenever a controller button is pressed
       */
   else if (strstr(device_name, "Amazon Fire TV Remote")
            || strstr(device_name, "Nexus Remote")
            || strstr(device_name, "SHIELD Remote"))
   {
      android->pads_connected = 0;
      port = 0;
      strlcpy(name_buf, device_name, sizeof(name_buf));
   }

   else if (strstr(device_name, "iControlPad-"))
      strlcpy(name_buf, "iControlPad HID Joystick profile", sizeof(name_buf));

   else if (strstr(device_name, "TTT THT Arcade console 2P USB Play"))
   {
      if (port == 0)
         strlcpy(name_buf, "TTT THT Arcade (User 1)", sizeof(name_buf));
      else if (port == 1)
         strlcpy(name_buf, "TTT THT Arcade (User 2)", sizeof(name_buf));
   }
   else if (strstr(device_name, "MOGA"))
      strlcpy(name_buf, "Moga IME", sizeof(name_buf));

      /* If device is keyboard only and didn't match any of the devices above
       * then assume it is a keyboard, register the id, and return unless the
       * maximum number of keyboards are already registered. */
   else if (source == AINPUT_SOURCE_KEYBOARD && kbd_num < MAX_NUM_KEYBOARDS)
   {
      kbd_id[kbd_num] = id;
      kbd_num++;
      return;
   }

      /* If the device is a keyboard, didn't match any of the devices above
       * and is designated as the physical keyboard, then assume it is a keyboard,
       * register the id, and return unless the
       * maximum number of keyboards are already registered. */
   else if ((source & AINPUT_SOURCE_KEYBOARD) && kbd_num < MAX_NUM_KEYBOARDS &&
            is_configured_as_physical_keyboard(vendorId, productId, device_name))
   {
      kbd_id[kbd_num] = id;
      kbd_num++;
      return;
   }

      /* if device was not keyboard only, yet did not match any of the devices
       * then try to autoconfigure as gamepad based on device_name. */
   else if (!string_is_empty(device_name))
      strlcpy(name_buf, device_name, sizeof(name_buf));

   if (strstr(android_app->current_ime, "net.obsidianx.android.mogaime"))
      strlcpy(name_buf, android_app->current_ime, sizeof(name_buf));
   else if (strstr(android_app->current_ime, "com.ccpcreations.android.WiiUseAndroid"))
      strlcpy(name_buf, android_app->current_ime, sizeof(name_buf));
   else if (strstr(android_app->current_ime, "com.hexad.bluezime"))
      strlcpy(name_buf, android_app->current_ime, sizeof(name_buf));

   if (port < 0) {
      for (int i = 0; i < MAX_USERS; ++i) {
         if (android->pad_states[i].id == -1) {
            port = i;
            break;
         }
      }

      if (port < 0) {
         return;
      }
   }

   input_autoconfigure_connect(
           name_buf,
           NULL,
           android_joypad.ident,
           port,
           vendorId,
           productId);

   android->pad_states[port].id = id;
   android_app->id[port] = id;
   android->pad_states[port].port = port;

   strlcpy(android->pad_states[port].name, name_buf,
           sizeof(android->pad_states[port].name));

   android->pads_connected++;
}

JNIEXPORT void JNICALL
Java_com_xugame_app_JoypadManager_removeJoystickNative(
        JNIEnv *env, jclass clazz,
        jint id
) {
   struct android_app   *android_app = (struct android_app*)g_android;
   input_driver_state_t *input_st    = input_state_get_ptr();
   android_input_t      *android     = (android_input_t*)input_st->current_data;
   int                   port        = -1;

   for (int i = 0; i < MAX_USERS; ++i) {
      if (android->pad_states[i].id == id) {
         port = i;
         break;
      }
   }

   if (port < 0) {
      return;
   }

   input_autoconfigure_disconnect(
           port,
           android_joypad.ident
   );

   android->pad_states[port].id = -1;
   android_app->id[port] = -1;
   android->pad_states[port].port = -1;
   android->pad_states[port].name[0] = '\0';

   android->pads_connected--;
}

static void *android_joypad_init(void *data) {
   struct android_app *android_app = (struct android_app*)g_android;
   JNIEnv                     *env  = jni_thread_getenv();

   if (!env)
      return NULL;

   CALL_VOID_STATIC_METHOD(
           env,
           android_app->beans.joypad_manager.clazz,
           android_app->beans.joypad_manager.initialize
   );

   return (void*)-1;
}

static int32_t android_joypad_button_state(
      struct android_app *android_app,
      uint8_t *buf,
      unsigned port, uint16_t joykey)
{
   unsigned hat_dir = GET_HAT_DIR(joykey);

   if (hat_dir)
   {
      unsigned h = GET_HAT(joykey);
      if (h > 0)
         return 0;

      switch (hat_dir)
      {
         case HAT_LEFT_MASK:
            return (android_app->hat_state[port][0] == -1);
         case HAT_RIGHT_MASK:
            return (android_app->hat_state[port][0] ==  1);
         case HAT_UP_MASK:
            return (android_app->hat_state[port][1] == -1);
         case HAT_DOWN_MASK:
            return (android_app->hat_state[port][1] ==  1);
         default:
            break;
      }
      /* hat requested and no hat button down */
   }
   else if (joykey < LAST_KEYCODE)
      return BIT_GET(buf, joykey);
   return 0;
}

static int32_t android_joypad_button(unsigned port, uint16_t joykey)
{
   struct android_app *android_app = (struct android_app*)g_android;
   uint8_t *buf                    = android_keyboard_state_get(port);

   if (port >= DEFAULT_MAX_PADS)
      return 0;

   return android_joypad_button_state(android_app, buf, port, joykey);
}

static int16_t android_joypad_axis_state(
      struct android_app *android_app,
      unsigned port, uint32_t joyaxis)
{
   if (AXIS_NEG_GET(joyaxis) < MAX_AXIS)
   {
      int16_t val = android_app->analog_state[port][AXIS_NEG_GET(joyaxis)];
      if (val < 0)
         return val;
   }
   else if (AXIS_POS_GET(joyaxis) < MAX_AXIS)
   {
      int16_t val = android_app->analog_state[port][AXIS_POS_GET(joyaxis)];
      if (val > 0)
         return val;
   }
   return 0;
}

static int16_t android_joypad_axis(unsigned port, uint32_t joyaxis)
{
   struct android_app *android_app = (struct android_app*)g_android;
   return android_joypad_axis_state(android_app, port, joyaxis);
}

static int16_t android_joypad_state(
      rarch_joypad_info_t *joypad_info,
      const struct retro_keybind *binds,
      unsigned port)
{
   unsigned i;
   int16_t ret                          = 0;
   struct android_app *android_app      = (struct android_app*)g_android;
   uint8_t *buf                         = android_keyboard_state_get(port);
   uint16_t port_idx                    = joypad_info->joy_idx;

   if (port_idx >= DEFAULT_MAX_PADS)
      return 0;

   for (i = 0; i < RARCH_FIRST_CUSTOM_BIND; i++)
   {
      /* Auto-binds are per joypad, not per user. */
      const uint64_t joykey  = (binds[i].joykey != NO_BTN)
         ? binds[i].joykey  : joypad_info->auto_binds[i].joykey;
      const uint32_t joyaxis = (binds[i].joyaxis != AXIS_NONE)
         ? binds[i].joyaxis : joypad_info->auto_binds[i].joyaxis;
      if ((uint16_t)joykey != NO_BTN 
            && android_joypad_button_state(
               android_app,
               buf,
               port_idx, (uint16_t)joykey))
         ret |= ( 1 << i);
      else if (joyaxis != AXIS_NONE &&
            ((float)abs(android_joypad_axis_state(
                  android_app, port_idx, joyaxis)) 
             / 0x8000) > joypad_info->axis_threshold)
         ret |= (1 << i);
   }

   return ret;
}

/**
 * 每 3s 检查一次是否有手柄插入
 */
static void android_joypad_poll(void) {
   static retro_time_t timeout = 0;
   struct android_app *android_app = (struct android_app*)g_android;
   JNIEnv                     *env  = jni_thread_getenv();
   retro_time_t now = cpu_features_get_time_usec();

   if (!env)
      return;

   if (!timeout || now >= timeout) {
      timeout = now + 3000000;
      CALL_VOID_STATIC_METHOD(
              env,
              android_app->beans.joypad_manager.clazz,
              android_app->beans.joypad_manager.pollInputDevices
      );
   }
}

static bool android_joypad_query_pad(unsigned pad)
{
   return (pad < MAX_USERS);
}

static void android_joypad_destroy(void)
{
   unsigned i, j;
   struct android_app *android_app = (struct android_app*)g_android;
   JNIEnv                     *env = jni_thread_getenv();

   for (i = 0; i < DEFAULT_MAX_PADS; i++)
   {
      for (j = 0; j < 2; j++)
         android_app->hat_state[i][j]    = 0;
      for (j = 0; j < MAX_AXIS; j++)
         android_app->analog_state[i][j] = 0;
   }

   for (i = 0; i < MAX_USERS; i++) {
      android_app->rumble_last_strength_strong[i] = 0;
      android_app->rumble_last_strength_weak  [i] = 0;
      android_app->rumble_last_strength       [i] = 0;
      android_app->id                         [i] = 0;
   }

   if (!env)
      return;

   CALL_VOID_STATIC_METHOD(
           env,
           android_app->beans.joypad_manager.clazz,
           android_app->beans.joypad_manager.uninitialize
   );
}

static void android_input_set_rumble_internal(
      uint16_t strength,
      uint16_t *last_strength_strong,
      uint16_t *last_strength_weak,
      uint16_t *last_strength,
      int8_t   id,
      enum retro_rumble_effect effect
      )
{
   JNIEnv *env           = (JNIEnv*)jni_thread_getenv();
   uint16_t new_strength = 0;

   if (!env)
      return;

   if (effect == RETRO_RUMBLE_STRONG)
   {
      new_strength          = strength | *last_strength_weak;
      *last_strength_strong = strength;
   }
   else if (effect == RETRO_RUMBLE_WEAK)
   {
      new_strength         = strength | *last_strength_strong;
      *last_strength_weak  = strength;
   }

   if (new_strength != *last_strength)
   {
      /* trying to send this value as a JNI param without 
       * storing it first was causing 0 to be seen on the other side ?? */
      int strength_final   = (255.0f / 65535.0f) * (float)new_strength;

      CALL_VOID_METHOD_PARAM(env, g_android->activity->clazz,
            g_android->doVibrate, (jint)id, (jint)RETRO_RUMBLE_STRONG, (jint)strength_final, (jint)0);

      *last_strength = new_strength;
   }
}

static bool android_joypad_rumble(unsigned port,
      enum retro_rumble_effect type, uint16_t strength)
{
   settings_t *settings            = config_get_ptr();
   struct android_app *android_app = (struct android_app*)g_android;
   bool enable_device_vibration    = settings->bools.enable_device_vibration;

   if (!android_app || !android_app->doVibrate)
      return false;

   if (enable_device_vibration)
   {
      static uint16_t last_strength_strong = 0;
      static uint16_t last_strength_weak   = 0;
      static uint16_t last_strength        = 0;

      if (port != 0)
         return false;

      android_input_set_rumble_internal(
            strength,
            &last_strength_strong,
            &last_strength_weak,
            &last_strength,
            -1,
            type);
   }
   else
   {
      android_input_set_rumble_internal(
            strength,
            &android_app->rumble_last_strength_strong[port],
            &android_app->rumble_last_strength_weak[port],
            &android_app->rumble_last_strength[port],
            android_app->id[port],
            type);
   }

   return true;
}

input_device_driver_t android_joypad = {
   android_joypad_init,
   android_joypad_query_pad,
   android_joypad_destroy,
   android_joypad_button,
   android_joypad_state,
   NULL,
   android_joypad_axis,
   android_joypad_poll,
   android_joypad_rumble,
   NULL,
   android_joypad_name,
   "android",
};
