#!/usr/bin/env bash
# android_input_keyevent — Send key event via adb shell input keyevent.
# Accepts aliases (BACK, HOME, POWER, ENTER, MENU, RECENT_APPS),
# raw numeric codes, or explicit KEYCODE_* names.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=adb_wsl.sh
source "$SCRIPT_DIR/adb_wsl.sh"

android_input_keyevent() {
    # Resolve serial (consumes --serial <S> from args, remainder in ADB_PICK_REST)
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    local raw="${1:-}"
    if [[ -z "$raw" ]]; then
        echo "android_input_keyevent: missing keycode argument" >&2
        return 1
    fi

    # Resolve alias → KEYCODE_*
    local keycode
    case "${raw^^}" in
        BACK)         keycode="KEYCODE_BACK" ;;
        HOME)         keycode="KEYCODE_HOME" ;;
        POWER)        keycode="KEYCODE_POWER" ;;
        ENTER)        keycode="KEYCODE_ENTER" ;;
        MENU)         keycode="KEYCODE_MENU" ;;
        RECENT_APPS)  keycode="KEYCODE_APP_SWITCH" ;;
        VOLUME_UP)    keycode="KEYCODE_VOLUME_UP" ;;
        VOLUME_DOWN)  keycode="KEYCODE_VOLUME_DOWN" ;;
        *)
            # Already has KEYCODE_ prefix or is a raw number → pass through
            if [[ "${raw^^}" == KEYCODE_* ]] || [[ "$raw" =~ ^[0-9]+$ ]]; then
                keycode="$raw"
            else
                # Unknown alias: uppercase and prepend KEYCODE_
                keycode="KEYCODE_${raw^^}"
            fi
            ;;
    esac

    adb_s "$serial" shell input keyevent "$keycode"
    echo "key: $keycode on $serial"
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    android_input_keyevent "$@"
fi
