#!/usr/bin/env python3
# Mundo Games Toolbox - arreglo-harley. Escribe (por stdout) las lineas de controles del lindbergh.conf
# del loader viejo para el mando del jugador 1, con el mismo mapeo que usa el generador lindbergh de
# Batocera 43.1 para Harley con un mando (lindberghGenerator.py, "hdkotr"):
#   R2 = gas, L2 = freno, stick izquierdo = direccion, x = cambiar vista, L1/R1 = cambios, b = BUTTON_1,
#   Start, Select = moneda, L3 = service, cruceta = menus.
# Jugador 1: MG_HARLEY_P1DEV y MG_HARLEY_P1GUID (los exporta el bloque del lanzador con -p1devicepath y
# -p1guid de ES); si faltan, la primera linea de SDL_GAMECONTROLLERCONFIG y el dispositivo con ese GUID.
# Los codigos evdev salen de es_input.cfg (atributo code; primero el del usuario, luego el del sistema).
# Un gatillo que es boton (KEY) tambien vale como ANALOGUE: el loader lo toma como pisado a fondo o suelto.
# Si algo falta, no escribe nada y el loader usa el teclado.
import os
import sys
import xml.etree.ElementTree as ET

ES_INPUTS = ("/userdata/system/configs/emulationstation/es_input.cfg", "/usr/share/emulationstation/es_input.cfg")
ABS_HAT0X = 16

# entrada de ES -> entrada del loader (pad, Harley)
MAPEO = {
    "b": "PLAYER_1_BUTTON_1",
    "x": "PLAYER_1_BUTTON_2",          # cambiar vista
    "pagedown": "PLAYER_1_BUTTON_3",   # subir cambio
    "pageup": "PLAYER_1_BUTTON_4",     # bajar cambio
    "start": "PLAYER_1_BUTTON_START",
    "select": "PLAYER_1_COIN",
    "l3": "PLAYER_1_BUTTON_SERVICE",
    "up": "PLAYER_1_BUTTON_UP",
    "down": "PLAYER_1_BUTTON_DOWN",
    "left": "PLAYER_1_BUTTON_LEFT",
    "right": "PLAYER_1_BUTTON_RIGHT",
    "r2": "ANALOGUE_1",                # gas
    "joystick1left": "ANALOGUE_2",     # direccion
    "l2": "ANALOGUE_4",                # freno
}
HAT = {1: (1, "MIN"), 4: (1, "MAX"), 8: (0, "MIN"), 2: (0, "MAX")}   # valor -> (eje 0=X 1=Y, lado)


def guid_p1():
    guid = os.environ.get("MG_HARLEY_P1GUID", "").strip().lower()
    if len(guid) == 32:
        return guid
    for linea in os.environ.get("SDL_GAMECONTROLLERCONFIG", "").splitlines():
        guid = linea.split(",", 1)[0].strip().lower()
        if len(guid) == 32:
            return guid
    return None


def le16(guid, i):
    return int(guid[i + 2:i + 4] + guid[i:i + 2], 16)


def dispositivo(guid, nombre, codigos):
    try:
        import evdev
    except ImportError:
        return None
    bus, vendor, product = le16(guid, 0), le16(guid, 8), le16(guid, 16)
    candidatos = []
    for ruta in evdev.list_devices():
        try:
            d = evdev.InputDevice(ruta)
        except OSError:
            continue
        if (d.info.bustype, d.info.vendor, d.info.product) != (bus, vendor, product):
            continue
        teclas = set(d.capabilities().get(evdev.ecodes.EV_KEY, []))
        puntos = len(codigos & teclas) + (5 if d.name == nombre else 0)
        candidatos.append((puntos, ruta))
    if not candidatos:
        return None
    candidatos.sort(key=lambda c: (-c[0], int(c[1].rsplit("event", 1)[-1])))
    return candidatos[0][1]


def main():
    guid = guid_p1()
    if not guid:
        return
    conf = None
    for archivo in ES_INPUTS:
        try:
            raiz = ET.parse(archivo).getroot()
        except (OSError, ET.ParseError):
            continue
        conf = next((c for c in raiz.iter("inputConfig") if (c.get("deviceGUID") or "").lower() == guid), None)
        if conf is not None:
            break
    if conf is None:
        return
    entradas = {i.get("name"): i for i in conf.iter("input")}
    codigos = {int(i.get("code")) for i in entradas.values() if i.get("type") == "button" and i.get("code")}
    ruta = os.environ.get("MG_HARLEY_P1DEV", "")
    if not ruta.startswith("/dev/input/event") or not os.path.exists(ruta):
        ruta = dispositivo(guid, conf.get("deviceName"), codigos)
    if not ruta:
        return
    for nombre_es, nombre_loader in MAPEO.items():
        i = entradas.get(nombre_es)
        if i is None:
            continue
        tipo, valor = i.get("type"), int(i.get("value") or 0)
        if tipo == "button" and i.get("code"):
            print(f"{nombre_loader} {ruta}:KEY:{i.get('code')}")
        elif tipo == "hat" and valor in HAT:
            eje, lado = HAT[valor]
            print(f"{nombre_loader} {ruta}:ABS:{ABS_HAT0X + 2 * int(i.get('id')) + eje}:{lado}")
        elif tipo == "axis" and i.get("code"):
            if nombre_loader.startswith("ANALOGUE"):
                print(f"{nombre_loader} {ruta}:ABS:{i.get('code')}")
            else:
                print(f"{nombre_loader} {ruta}:ABS:{i.get('code')}:{'MIN' if valor < 0 else 'MAX'}")


if __name__ == "__main__":
    try:
        main()
    except Exception as e:  # nunca romper el arranque del juego por los controles
        print(f"# mandos.py: {e}", file=sys.stderr)
