#!/usr/bin/python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Subscribe to InputPlumber dbus0 InputEvent signals and toggle
the joymouse/gamepad profile when the Guide button fires.

InputPlumber's DBusDevice target emits

    org.shadowblip.Input.DBusDevice.InputEvent  (string action, double value)

on path /org/shadowblip/InputPlumber/devices/target/dbus0. Both
the default gamepad profile and pocketds-joymouse.yaml route the
Guide button to `dbus: ui_guide`, so this listener fires on Guide
press regardless of which profile is currently active.
"""
import subprocess
import time

import dbus
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

DBusGMainLoop(set_as_default=True)

# 200 ms debounce — Guide press generates two events (down + up)
# at value=1.0 and value=0.0; we only act on press (value > 0.5)
# but still want a guard against held-down-fingers.
LAST_FIRE = 0.0


def on_input_event(action, value):
    global LAST_FIRE
    if action != "ui_guide":
        return
    if value < 0.5:  # release event
        return
    now = time.monotonic()
    if now - LAST_FIRE < 0.2:
        return
    LAST_FIRE = now
    subprocess.Popen(
        ["/usr/bin/pocketds-toggle-joymouse"],
        stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
    )


bus = dbus.SystemBus()
bus.add_signal_receiver(
    on_input_event,
    signal_name="InputEvent",
    dbus_interface="org.shadowblip.Input.DBusDevice",
    bus_name="org.shadowblip.InputPlumber",
)

GLib.MainLoop().run()
