
#include "environ/environ.h"
#include "utils.h"
#include "native_hooks.h"
#include "log.h"
#include "SDL3/SDL.h"

#include <bytehook.h>
#include <dlfcn.h>
#include <jni.h>
#include <stdlib.h>

DECL_DLSYM(SDL_InitSubSystem)
DECL_DLSYM(SDL_SetHint);
DECL_DLSYM(SDL_SetTextInputArea);
DECL_DLSYM(SDL_SetError);


static bool custom_SDL_InitSubSystem_Func(SDL_InitFlags flags) {
    // Call notifyLauncher on SDL_InitSubSystem, this sets up all the JNI stuff needed by SDL.
    TRY_ATTACH_ENV(dvm_env, pojav_environ->dalvikJavaVMPtr, "SDL_InitSubSystem failed!",
            SET_DLSYM_PTR(dlopen("libSDL3.so", RTLD_NOLOAD), SDL_SetError);
            if (SDL_SetError_p) SDL_SetError_p("Failed to load SDL launcher integration android-side. This is not an SDL bug, please contact the launcher developer.");
            return false;
            );

    // Just in case of bozo
    jint safeFlags;
    if (flags > INT32_MAX) {
        safeFlags = -1;
    } else safeFlags = (jint)flags;

    notifyLauncher(dvm_env, NOTIF_TYPE_SDL, (int[]){ACTION_INIT_LAUNCHER_INTEGRATION, safeFlags}, 2);

    // This is the normal for the launcher, the default in SDL is false.
    SET_DLSYM_PTR(dlopen("libSDL3.so", RTLD_NOLOAD), SDL_SetHint);
    if (SDL_SetHint_p) SDL_SetHint_p("SDL_RETURN_KEY_HIDES_IME", "true");
    // FIXME: MobileGlues has issues with passing in the proper EGL params to make this work
    const char *egl = getenv("POJAVEXEC_EGL");
    if (egl && strcmp(egl, "libmobileglues.so") == 0) {
        SDL_SetHint_p("SDL_OPENGL_FORCE_SRGB_FRAMEBUFFER", "0");
    }

    // Call original func after doing all the needed setup
    bool r = BYTEHOOK_CALL_PREV(custom_SDL_InitSubSystem_Func, SDL_InitSubSystem_t, flags);
    BYTEHOOK_POP_STACK();
    return r;
}

//// This doesn't work because lwjgl doesn't use plt/got to access the bindings, fml
//static bool custom_SDL_SetTextInputArea_Func(SDL_Window *window, const SDL_Rect *rect, int cursor) {
//    TRY_ATTACH_ENV(SDL_GetTextInputArea);
//    notifyLauncher(dvm_env, NOTIF_TYPE_SDL, (int[]) {
//        ACTION_SEND_TEXTBOX_RECT,
//        rect->x, rect->y, rect->x + rect->w, rect->y + rect->h, cursor
//    }, 6);
//    int r = BYTEHOOK_CALL_PREV(custom_SDL_SetTextInputArea_Func, SDL_SetTextInputArea_t, window, rect, cursor);
//    BYTEHOOK_POP_STACK();
//    return r;
//}


void create_sdl_hooks(bytehook_hook_all_t bytehook_hook_all_p) {
    // Don't set callee_path_name to anything besides NULL or else it won't be able to find the symbol
    bytehook_stub_t stub_SDL_InitSubSystem = bytehook_hook_all_p(NULL, "SDL_InitSubSystem", &custom_SDL_InitSubSystem_Func, NULL, NULL);
    LOGI("Successfully initialized SDL hooks, stubs: %p, %p\n", stub_SDL_InitSubSystem);
}