#!/usr/bin/env python3
import evdev
import subprocess
import time

DEVICE_NAMES = ["8BitDo NGC Modkit"]
BUTTON_MAP = {
    "304": "Return",    # A
    "305": None,        # B (non utilisé)
    "311": "Alt_L",     # R
    "307": "Right",     # X
    "308": "Left",      # Y
    # 318 (BTN_THUMBR) sera géré à part
}

def find_device():
    for path in evdev.list_devices():
        try:
            dev = evdev.InputDevice(path)
            if any(dn in dev.name for dn in DEVICE_NAMES):
                return path
        except Exception:
            continue
    return None

def is_dolphin_running():
    try:
        output = subprocess.check_output(["flatpak", "ps"]).decode()
        return "org.DolphinEmu.dolphin-emu" in output
    except Exception:
        return False

def press_key(key, press):
    # press=True -> key down, press=False -> key up
    action = "keydown" if press else "keyup"
    subprocess.run(["xdotool", action, key])

def handle_device(dev_path):
    dev = evdev.InputDevice(dev_path)
    try:
        for event in dev.read_loop():
            if event.type != evdev.ecodes.EV_KEY:
                continue

            key_code = str(event.code)

            # cas spécial : joystick jaune (BTN_THUMBR, code 318)
            if key_code == "318" and event.value == 1:  # pression
                press_key("Alt_L", True)
                time.sleep(0.02)
                press_key("Escape", True)
                time.sleep(0.05)
                press_key("Escape", False)
                press_key("Alt_L", False)
                continue

            if key_code in BUTTON_MAP:
                mapped_key = BUTTON_MAP[key_code]
                if mapped_key is not None:
                    press_key(mapped_key, event.value == 1)

    except OSError:
        dev.close()
        raise

def main():
    connected = False
    time.sleep(5)  # délai pour que le serveur graphique soit prêt
    while True:
        dev_path = find_device()
        if dev_path and not connected:
            print(f"[+] Manette connectée: {dev_path}")
            connected = True
            if not is_dolphin_running():
                try:
                    subprocess.Popen(["flatpak", "run", "org.DolphinEmu.dolphin-emu"])
                except Exception as e:
                    print(f"[!] Impossible de lancer Dolphin: {e}")
            try:
                handle_device(dev_path)
            except OSError:
                print("[-] Manette déconnectée")
                connected = False
                try:
                    subprocess.Popen(["flatpak", "kill", "org.DolphinEmu.dolphin-emu"])
                except Exception as e:
                    print(f"[!] Impossible de tuer Dolphin: {e}")
        elif not dev_path and connected:
            print("[-] Manette déconnectée")
            connected = False
        time.sleep(1)

if __name__ == "__main__":
    main()
