#!/usr/bin/env python3
# probeInput.py - work out how to get joystick input into VICE on a headless display.  The options
# menu keeps its highlighted row in $91D5 and the raster IRQ copies the port 2 joystick into zp_5D,
# so both are readable proof that a synthetic key press actually arrived.
import os
import subprocess
import sys
import time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from viceHarness import ViceSession, aciaArgs, SCRATCH


def peek(session, addr, count=1):
    out = session.mon(f"m {addr:04x} {addr+count-1:04x}")
    return out


def main():
    disk = os.path.abspath(sys.argv[1])
    session = ViceSession(disk, f"{SCRATCH}/probe.vice.log", aciaArgs(), label="probe")
    try:
        session.connect()
        session.bootPastLoader()
        win = session.findWindow()
        time.sleep(10)
        subprocess.run(["xdotool", "windowactivate", "--sync", win], env=session.env, check=False)
        subprocess.run(["xdotool", "windowfocus", "--sync", win], env=session.env, check=False)
        time.sleep(1)

        session.enterMonitor()
        peek(session, 0x91D5, 2)
        peek(session, 0x005D, 6)
        session.sock.sendall(b"x\n")
        session.recv(3)

        for method in ("xtest", "window"):
            print(f"=== method {method}", flush=True)
            if method == "xtest":
                subprocess.run(["xdotool", "keydown", "KP_8"], env=session.env, check=False)
            else:
                subprocess.run(["xdotool", "keydown", "--window", win, "KP_8"], env=session.env,
                               check=False)
            time.sleep(0.6)
            session.enterMonitor()
            peek(session, 0x005D, 6)
            peek(session, 0x91D5, 2)
            session.sock.sendall(b"x\n")
            session.recv(3)
            if method == "xtest":
                subprocess.run(["xdotool", "keyup", "KP_8"], env=session.env, check=False)
            else:
                subprocess.run(["xdotool", "keyup", "--window", win, "KP_8"], env=session.env,
                               check=False)
            time.sleep(0.6)
            session.enterMonitor()
            peek(session, 0x91D5, 2)
            session.sock.sendall(b"x\n")
            session.recv(3)
    finally:
        session.close()


main()
