package io.github.madjacket.kat5200;

import android.app.UiModeManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.view.InputDevice;
import org.libsdl.app.SDLActivity;

/**
 * kat5200's Android entry point.  SDLActivity (from the SDL3 .aar) loads the
 * libraries listed below in order, then calls SDL_main in the last one
 * (libkat5200.so).  SDL_main is our normal main(), redefined via
 * &lt;SDL3/SDL_main.h&gt; in kat5200.c under __ANDROID__.
 */
public class MainActivity extends SDLActivity {

    /**
     * True when running on Android TV (a leanback / 10-foot device).  Cached on
     * first query so the native side can read it cheaply over JNI
     * (pc_is_android_tv in sdl_if.c) to pick fixed-landscape orientation and a
     * larger UI scale floor.  Default true-unknown is avoided: -1 = not yet
     * resolved, 0 = handheld, 1 = TV.
     */
    private static int sIsTv = -1;

    @Override
    protected String[] getLibraries() {
        return new String[] {
            "SDL3",
            "SDL3_image",
            "kat5200"
        };
    }

    /**
     * Called from native code (sdl_if.c) via JNI.  Returns true on Android TV.
     * Resolves lazily from UiModeManager and caches the result.
     */
    public static boolean isAndroidTv() {
        if (sIsTv < 0) {
            Context ctx = getContext();
            if (ctx == null)
                return false;   /* SDL context not ready: stay unresolved, retry later */
            sIsTv = detectTv(ctx) ? 1 : 0;
        }
        return sIsTv == 1;
    }

    /**
     * Called once from native startup to decide whether Android TV should offer
     * the mouse-heavy debugger UI.  Hotplug is intentionally ignored until the
     * next app start so we do not enumerate input devices every GUI frame.
     */
    public static boolean hasPointingMouse() {
        int[] ids = InputDevice.getDeviceIds();

        for (int id : ids) {
            InputDevice dev = InputDevice.getDevice(id);
            int sources;

            if (dev == null)
                continue;

            sources = dev.getSources();
            if ((sources & InputDevice.SOURCE_MOUSE) == InputDevice.SOURCE_MOUSE)
                return true;
            if (Build.VERSION.SDK_INT >= 26 &&
                    (sources & InputDevice.SOURCE_MOUSE_RELATIVE) ==
                    InputDevice.SOURCE_MOUSE_RELATIVE)
                return true;
        }

        return false;
    }

    private static boolean detectTv(Context ctx) {
        if (ctx == null)
            return false;
        UiModeManager uiMode =
            (UiModeManager) ctx.getSystemService(Context.UI_MODE_SERVICE);
        return uiMode != null
            && uiMode.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION;
    }

    /**
     * SDL pins the activity to the orientation matching the window's aspect
     * when it is first created (e.g. USER_PORTRAIT if launched in portrait), so
     * the app "sticks" to its launch orientation and never follows the sensor.
     * On a phone, ignore those calls and keep free rotation (matches the
     * manifest's fullUser; respects the system auto-rotate lock).  On a TV
     * there is no sensor and the UI is a fixed 10-foot landscape layout, so
     * lock to landscape instead.
     */
    @Override
    public void setRequestedOrientation(int requestedOrientation) {
        if (isAndroidTv())
            super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        else
            super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);
    }
}
