#!/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")

                # Botón principal de la ventana
                btn = Gtk.Button(label=f"{app} - {title}")
                btn.connect("clicked", self.on_button_clicked, address)
                self.box.pack_start(btn, False, False, 0)

                # Caja de botones de workspace
                ws_box = Gtk.Box(spacing=4)
                for i in range(1, 5):  # Workspaces 1-4
                    ws_btn = Gtk.Button(label=str(i))
                    ws_btn.set_size_request(30, 30)
                    ws_btn.connect("clicked", self.on_move_to_workspace, (address, i))
                    ws_box.pack_start(ws_btn, False, False, 0)

                self.box.pack_start(ws_box, False, False, 0)

        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_move_to_workspace(self, button, data):
        address, workspace = data

        # 1. Mostramos la ventana del scratchpad
        subprocess.run(["hyprctl", "dispatch", "togglespecialworkspace", "scratchpad"])
        
        # 2. Le damos foco a esa ventana
        subprocess.run(["hyprctl", "dispatch", "focuswindow", address])
        
        # 3. Movemos la ventana al workspace deseado (esto la saca del scratchpad)
        subprocess.run(["hyprctl", "dispatch", "movetoworkspace", str(workspace)])

        # 4. Cambiamos al workspace de destino
        subprocess.run(["hyprctl", "dispatch", "workspace", str(workspace)])

        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()

