#!/usr/bin/env bash
# android_emu_battery — Simulate battery state on Android emulator (level + charging).
# Usage: android_emu_battery [--serial <S>] <level 0-100> [--charging <true|false>]

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

android_emu_battery() {
    # Resolve serial (consumes --serial from args, leaves rest in ADB_PICK_REST)
    adb_pick_serial "$@" || exit 3
    local serial="$ADB_PICK_SERIAL"
    set -- "${ADB_PICK_REST[@]}"

    # Require serial to be an emulator
    if [[ "$serial" != emulator-* ]]; then
        echo "android_emu_battery: serial '$serial' is not an emulator (must start with emulator-)." >&2
        return 1
    fi

    # Parse remaining args: positional level + --charging
    local level=""
    local charging=""

    while [[ $# -gt 0 ]]; do
        case "$1" in
            --charging)
                charging="$2"
                shift 2
                ;;
            --charging=*)
                charging="${1#--charging=}"
                shift
                ;;
            -*)
                echo "android_emu_battery: unknown flag '$1'." >&2
                return 1
                ;;
            *)
                if [[ -z "$level" ]]; then
                    level="$1"
                fi
                shift
                ;;
        esac
    done

    # Validate level
    if [[ -z "$level" ]]; then
        echo "android_emu_battery: level is required (0-100)." >&2
        return 1
    fi
    if ! [[ "$level" =~ ^[0-9]+$ ]] || (( level < 0 || level > 100 )); then
        echo "android_emu_battery: invalid level '$level' — must be integer 0-100." >&2
        return 1
    fi

    # Set battery level
    adb_s "$serial" emu power capacity "$level" || {
        echo "android_emu_battery: failed to set capacity on $serial." >&2
        return 1
    }

    # Set charging state if requested
    local ch="<unchanged>"
    if [[ -n "$charging" ]]; then
        local ac_val
        case "$charging" in
            true)  ac_val="on"  ;;
            false) ac_val="off" ;;
            *)
                echo "android_emu_battery: --charging must be 'true' or 'false', got '$charging'." >&2
                return 1
                ;;
        esac
        adb_s "$serial" emu power ac "$ac_val" || {
            echo "android_emu_battery: failed to set AC charging on $serial." >&2
            return 1
        }
        ch="$charging"
    fi

    echo "battery: ${level}% [charging=${ch}] on ${serial}"
}

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