package de.ladkau.questshock;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

/**
 * The small main menu launcher quad (see OverlayPanel for the shared off-
 * screen-render/touch/cursor plumbing this builds on) - just a "Keyboard"
 * button for now. Toggled by the controller's menu button (see
 * xr_input.c); its "Keyboard" click only opens the (fully independent)
 * keyboard overlay quad via nativeShowKeyboard() - it never touches this
 * panel's own visibility, so both can be shown together (see
 * KeyboardOverlay for the keyboard itself).
 */
public class MenuOverlay extends OverlayPanel {
    // Matches xr_session.c's MENU_WIDTH/MENU_HEIGHT swapchain size - fixed,
    // not tied to any real display metric, since this tree is never shown
    // in a real window.
    private static final int WIDTH = 512;
    private static final int HEIGHT = 256;

    private static MenuOverlay instance;

    private MenuOverlay(Activity activity) {
        super(activity, WIDTH, HEIGHT);
    }

    @Override
    protected View buildContent() {
        FrameLayout panel = new FrameLayout(activity);
        panel.setBackgroundColor(0xFF202020);
        Button keyboardButton = new Button(activity);
        keyboardButton.setText("Keyboard");
        keyboardButton.setOnClickListener(v -> nativeShowKeyboard());
        keyboardButton.setOnTouchListener(CLICK_ON_TOUCH_UP);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(300, 100);
        lp.gravity = Gravity.CENTER;
        panel.addView(keyboardButton, lp);
        return panel;
    }

    // Opens the keyboard overlay quad (questshock_native.c ->
    // xr_overlay_set_visible(xr_session_get_keyboard_overlay(), true)) -
    // see KeyboardOverlay for the panel itself and its own Close button,
    // the only way to hide it again.
    private static native void nativeShowKeyboard();

    // Called from xr_overlay.c's xr_overlay_init_jni(), on the render
    // thread, right after it resolves this class via the activity's own
    // ClassLoader (plain FindClass() can't see app classes from a thread
    // that was attached to the JVM rather than spawned from Java).
    public static void nativeInit(Activity activity) {
        if (instance == null) {
            instance = new MenuOverlay(activity);
        }
    }

    public static byte[] nativeTakePixelsIfDirty() {
        return instance == null ? null : instance.takePixelsIfDirty();
    }

    public static void nativeDispatchTouch(final float u, final float v, final boolean down) {
        if (instance != null) {
            instance.dispatchTouch(u, v, down);
        }
    }

    public static void nativeUpdateCursor(final float u, final float v, final boolean visible) {
        if (instance != null) {
            instance.dispatchUpdateCursor(u, v, visible);
        }
    }
}
