// android.system.Os has no public chdir() (confirmed against the actual
// API 34 stub jar - Java has no way to change a process's working
// directory at all). This is the one bit of native code QuestShockActivity
// needs, compiled into the same "main" library as engine/ (see
// android/engine-patches/01-android-shared-lib.patch's ANDROID_EXTRA_SOURCES)
// - engine/ itself is never modified.
#include <jni.h>
#include <unistd.h>

#include <SDL.h>

#include "xr_overlay.h"
#include "xr_session.h"

JNIEXPORT void JNICALL
Java_de_ladkau_questshock_QuestShockActivity_nativeChdir(JNIEnv *env, jclass clazz, jstring path) {
    const char *cpath = (*env)->GetStringUTFChars(env, path, NULL);
    chdir(cpath);
    (*env)->ReleaseStringUTFChars(env, path, cpath);
}

// KeyboardOverlay's hand-built on-screen keyboard (see
// KeyboardOverlay.commitPrintableChar()) has no real Android IME session
// behind it, so printable characters can't reach the game via Android's
// usual IME path - instead this builds and pushes an SDL_TEXTINPUT event
// directly, the same event type/shape SDL's own Android backend pushes for
// typed text, using only the public SDL_Event/SDL_PushEvent API. The
// engine's pump_events() (sdl_events.c) only picks up printable characters
// from this event, not from SDL_KEYDOWN (see handleKeyPress() in
// KeyboardOverlay.java for why).
JNIEXPORT void JNICALL
Java_de_ladkau_questshock_KeyboardOverlay_nativeSendPrintableChar(JNIEnv *env, jclass clazz,
                                                                   jchar c) {
    SDL_Event event;
    SDL_zero(event);
    event.type = SDL_TEXTINPUT;
    event.text.timestamp = SDL_GetTicks();
    event.text.windowID = 0;
    event.text.text[0] = (char)c;
    event.text.text[1] = '\0';
    SDL_PushEvent(&event);
}

// KeyboardOverlay's title-bar Close button - the keyboard is a fully
// independent overlay quad from the menu launcher (see xr_overlay.h), so
// this is the only way to hide it once it's open; the controller's menu
// button only ever affects the menu launcher.
JNIEXPORT void JNICALL
Java_de_ladkau_questshock_KeyboardOverlay_nativeRequestClose(JNIEnv *env, jclass clazz) {
    xr_overlay_set_visible(xr_session_get_keyboard_overlay(), false);
}

// MenuOverlay's "Keyboard" button - only opens the keyboard overlay, never
// touches the menu launcher's own visibility, so both can be shown
// together.
JNIEXPORT void JNICALL
Java_de_ladkau_questshock_MenuOverlay_nativeShowKeyboard(JNIEnv *env, jclass clazz) {
    xr_overlay_set_visible(xr_session_get_keyboard_overlay(), true);
}
