#!/usr/bin/env python3
from pydbus import SessionBus
from gi.repository import GLib
import subprocess

bus = SessionBus()
loop = GLib.MainLoop()

connected_players = {}
inhibit_proc = None
inhibited = False

def handle_properties_changed(player_name):
    def handler(interface, changed, invalidated):
        global inhibited, inhibit_proc

        if "PlaybackStatus" in changed:
            status = changed["PlaybackStatus"]
            print(f"[{player_name}] PlaybackStatus changed: {status}")

            if status == "Playing" and not inhibited:
                print(f"[{player_name}] ▶️ Inhibiting idle")
                inhibit_proc = subprocess.Popen(["hypridle-inhibit", "sleep"])
                inhibited = True
            elif status != "Playing" and inhibited:
                print(f"[{player_name}] ⏸️ Stopping inhibit")
                if inhibit_proc:
                    inhibit_proc.terminate()
                inhibited = False

    return handler

def connect_player(name):
    if name in connected_players:
        return
    try:
        player = bus.get(name, "/org/mpris/MediaPlayer2")
        player.onPropertiesChanged = handle_properties_changed(name)
        connected_players[name] = player
        print(f" Connected to MPRIS player: {name}")
    except Exception as e:
        print(f" Failed to connect to {name}: {e}")

def connect_all_players():
    dbus = bus.get(".DBus")
    names = dbus.ListNames()
    for name in names:
        if name.startswith("org.mpris.MediaPlayer2."):
            connect_player(name)


def on_name_owner_changed(conn, sender, object, interface, signal, params):
    name, old_owner, new_owner = params
    if name.startswith("org.mpris.MediaPlayer2.") and new_owner:
        print(f" New player appeared: {name}")
        connect_player(name)


# Subscribir a nuevos reproductores que se conecten al bus
bus.con.signal_subscribe(
    None,
    "org.freedesktop.DBus",
    "NameOwnerChanged",
    None,
    None,
    0,
    on_name_owner_changed
)


# Conectar a los reproductores activos en el momento
connect_all_players()

# Iniciar loop principal
print(" MPRIS idle inhibitor started.")
loop.run()

