#!/usr/bin/env python3

import subprocess
import json
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gtk, Gdk

class ScratchpadPanel(Gtk.Window):
    def __init__(self):
        super().__init__(title="Scratchpad Windows")
        self.set_border_width(10)
        self.set_default_size(300, 200)
        self.set_keep_above(True)
        self.set_type_hint(Gdk.WindowTypeHint.DIALOG)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.set_resizable(False)

        self.box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
        self.add(self.box)

        self.populate()

    def populate(self):
        clients = self.get_scratchpad_clients()
        if not clients:
            label = Gtk.Label(label="No hay ventanas en el scratchpad.")
            self.box.pack_start(label, True, True, 0)
        else:
            for client in clients:
                title = client.get("title", "Sin título")
                app = client.get("class", "App")
                address = client.get("address")
                btn = Gtk.Button(label=f"{app} - {title}")
                btn.connect("clicked", self.on_button_clicked, address)
                self.box.pack_start(btn, True, True, 0)

        # Agregar botón "Salir" al final
        quit_btn = Gtk.Button(label="❌ Salir")
        quit_btn.connect("clicked", self.on_quit_clicked)
        self.box.pack_start(quit_btn, False, False, 10)

        self.show_all()

    def on_button_clicked(self, button, address):
        subprocess.run(["hyprctl", "dispatch", "togglespecialworkspace", "scratchpad"])
        subprocess.run(["hyprctl", "dispatch", "focuswindow", address])
        self.destroy()

    def on_quit_clicked(self, button):
        self.destroy()

    def get_scratchpad_clients(self):
        try:
            result = subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True)
            clients = json.loads(result.stdout)
            scratchpad = [
                c for c in clients
                if c.get("workspace", {}).get("name") == "special:scratchpad"
            ]
            return scratchpad
        except Exception as e:
            print(f"Error obteniendo clientes: {e}")
            return []

def main():
    win = ScratchpadPanel()
    win.connect("destroy", Gtk.main_quit)
    Gtk.main()

if __name__ == "__main__":
    main()

