#!/usr/bin/env python3
"""Authentic Windows XP Desktop Icons + Recycle Bin + Right-Click Menu daemon (BACKGROUND layer)."""

import fcntl
import os
import shutil
import signal
import subprocess
import sys
import time
from pathlib import Path

os.environ.setdefault("DCONF_PROFILE", "/home/carsten/.config/hypr/dconf/profile")

import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("GdkPixbuf", "2.0")
gi.require_version("GtkLayerShell", "0.1")
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib, GtkLayerShell, Pango

LOCK_PATH = f"/run/user/{os.getuid()}/xp-desktop.lock"
TRASH_FILES = Path.home() / ".local/share/Trash/files"
TRASH_INFO = Path.home() / ".local/share/Trash/info"
DESKTOP_DIR = Path.home() / "Desktop"
SOUND_SCRIPT = "/home/carsten/.config/hypr/scripts/xp-sound.sh"

DESKTOP_CSS = b"""
window#xp-desktop-win {
    background-color: transparent;
}
.xp-desk-item {
    background-color: transparent;
    border: 1px solid transparent;
    border-radius: 2px;
    padding: 5px 4px 4px 4px;
    min-width: 74px;
}
.xp-desk-item.selected {
    background-color: rgba(49, 106, 197, 0.55);
    border: 1px dotted rgba(255, 255, 255, 0.85);
}
.xp-desk-label {
    font-family: "Tahoma", sans-serif;
    font-size: 8.5pt;
    color: #FFFFFF;
    text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.92), 0px 1px 2px rgba(0, 0, 0, 0.85);
}
.xp-desk-item.selected .xp-desk-label {
    background-color: #316AC5;
    color: #FFFFFF;
    text-shadow: none;
    padding: 0px 2px;
}
"""


def launch(cmd):
    subprocess.Popen(["hyprctl", "dispatch", "exec", cmd],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def trash_has_items():
    try:
        return TRASH_FILES.is_dir() and any(TRASH_FILES.iterdir())
    except OSError:
        return False


def empty_recycle_bin(on_done=None):
    if not trash_has_items():
        return
    for d in (TRASH_FILES, TRASH_INFO):
        if d.is_dir():
            for p in d.iterdir():
                try:
                    if p.is_dir() and not p.is_symlink():
                        shutil.rmtree(p)
                    else:
                        p.unlink()
                except OSError:
                    pass
    subprocess.Popen([SOUND_SCRIPT, "recycle"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    if on_done:
        on_done()


def load_icon_32(path_list):
    for p in path_list:
        if p and os.path.exists(p):
            try:
                return GdkPixbuf.Pixbuf.new_from_file_at_scale(p, 32, 32, True)
            except Exception:
                continue
    return None


class XPDesktop(Gtk.Window):
    def __init__(self):
        super().__init__(type=Gtk.WindowType.TOPLEVEL)
        self.set_name("xp-desktop-win")
        self.set_decorated(False)
        self.set_app_paintable(True)
        visual = self.get_screen().get_rgba_visual()
        if visual:
            self.set_visual(visual)

        GtkLayerShell.init_for_window(self)
        GtkLayerShell.set_layer(self, GtkLayerShell.Layer.BACKGROUND)
        GtkLayerShell.set_namespace(self, "xp-desktop")
        for edge in (GtkLayerShell.Edge.TOP, GtkLayerShell.Edge.BOTTOM, GtkLayerShell.Edge.LEFT, GtkLayerShell.Edge.RIGHT):
            GtkLayerShell.set_anchor(self, edge, True)
        GtkLayerShell.set_margin(self, GtkLayerShell.Edge.BOTTOM, 30)
        GtkLayerShell.set_exclusive_zone(self, -1)
        GtkLayerShell.set_keyboard_mode(self, GtkLayerShell.KeyboardMode.NONE)

        prov = Gtk.CssProvider()
        prov.load_from_data(DESKTOP_CSS)
        Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(), prov, Gtk.STYLE_PROVIDER_PRIORITY_USER)

        self.bg_eb = Gtk.EventBox()
        self.bg_eb.set_visible_window(False)
        self.bg_eb.connect("button-press-event", self._on_bg_click)
        self.add(self.bg_eb)

        self.grid = Gtk.Grid()
        self.grid.set_row_spacing(10)
        self.grid.set_column_spacing(12)
        self.grid.set_margin_top(14)
        self.grid.set_margin_start(14)
        self.grid.set_halign(Gtk.Align.START)
        self.grid.set_valign(Gtk.Align.START)
        self.bg_eb.add(self.grid)

        self.item_boxes = []
        self.selected_idx = -1
        self.last_click = (-1, 0.0)
        self.last_trash_state = None
        self.active_menu = None

        self.rebuild()
        GLib.timeout_add(3000, self._poll_trash)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, lambda: (Gtk.main_quit(), False)[1])

    def _build_items(self):
        home = str(Path.home())
        full = trash_has_items()
        self.last_trash_state = full
        trash_icon = (
            "/usr/local/share/icons/luna/32x32/status/user-trash-full.png"
            if full else
            "/usr/local/share/icons/luna/32x32/places/user-trash.png"
        )
        items = [
            {
                "label": "My Documents",
                "icons": ["/usr/local/share/icons/luna/32x32/places/folder-documents.png"],
                "cmd": f"thunar {home}/Documents",
                "kind": "system",
            },
            {
                "label": "My Computer",
                "icons": ["/usr/local/share/icons/luna/32x32/devices/computer.png"],
                "cmd": f"thunar {home}",
                "kind": "system",
            },
            {
                "label": "My Network\nPlaces",
                "icons": ["/usr/local/share/icons/luna/32x32/places/network-workgroup.png"],
                "cmd": "nm-connection-editor",
                "kind": "system",
            },
            {
                "label": "Recycle Bin",
                "icons": [trash_icon, "/usr/local/share/icons/luna/32x32/places/user-trash.png"],
                "cmd": "thunar trash:///",
                "kind": "trash",
            },
            {
                "label": "Firefox",
                "icons": [
                    "/snap/firefox/current/usr/lib/firefox/browser/chrome/icons/default/default32.png",
                    "/usr/local/share/icons/luna/32x32/apps/internet-web-browser.png",
                ],
                "cmd": "firefox",
                "kind": "app",
            },
            {
                "label": "Command\nPrompt",
                "icons": ["/usr/local/share/icons/luna/32x32/apps/utilities-terminal.png"],
                "cmd": "ghostty",
                "kind": "app",
            },
        ]

        # Append real user files/folders from ~/Desktop
        if DESKTOP_DIR.is_dir():
            for p in sorted(DESKTOP_DIR.iterdir()):
                if p.name.startswith("."):
                    continue
                is_dir = p.is_dir()
                ic = (
                    "/usr/local/share/icons/luna/32x32/places/folder.png"
                    if is_dir else
                    "/usr/local/share/icons/luna/32x32/mimetypes/text-x-generic.png"
                )
                items.append({
                    "label": p.name,
                    "icons": [ic, "/usr/local/share/icons/luna/32x32/mimetypes/application-x-executable.png"],
                    "cmd": f"thunar '{p}'" if is_dir else f"xdg-open '{p}'",
                    "kind": "file",
                })
        return items

    def rebuild(self):
        for ch in self.grid.get_children():
            self.grid.remove(ch)
        self.item_boxes = []
        self.items = self._build_items()

        rows_per_col = 9
        for idx, item in enumerate(self.items):
            col = idx // rows_per_col
            row = idx % rows_per_col

            eb = Gtk.EventBox()
            eb.set_visible_window(False)
            eb.connect("button-press-event", self._on_item_click, idx)

            box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
            box.get_style_context().add_class("xp-desk-item")

            pb = load_icon_32(item["icons"])
            img = Gtk.Image.new_from_pixbuf(pb) if pb else Gtk.Image.new_from_icon_name("folder", Gtk.IconSize.DND)
            box.pack_start(img, False, False, 0)

            lbl = Gtk.Label(label=item["label"])
            lbl.set_justify(Gtk.Justification.CENTER)
            lbl.set_line_wrap(True)
            lbl.set_max_width_chars(12)
            lbl.set_ellipsize(Pango.EllipsizeMode.END)
            lbl.set_lines(2)
            lbl.get_style_context().add_class("xp-desk-label")
            box.pack_start(lbl, False, False, 0)

            eb.add(box)
            self.grid.attach(eb, col, row, 1, 1)
            self.item_boxes.append(box)

        self.grid.show_all()
        self._update_sel()

    def _poll_trash(self):
        cur = trash_has_items()
        if cur != self.last_trash_state:
            self.rebuild()
        return True

    def _update_sel(self):
        for i, box in enumerate(self.item_boxes):
            sc = box.get_style_context()
            if i == self.selected_idx:
                sc.add_class("selected")
            else:
                sc.remove_class("selected")

    def _on_item_click(self, _w, ev, idx):
        self.selected_idx = idx
        self._update_sel()
        item = self.items[idx]
        if ev.button == 1:
            now = time.monotonic()
            if ev.type == Gdk.EventType._2BUTTON_PRESS or (self.last_click[0] == idx and now - self.last_click[1] < 0.42):
                self.last_click = (-1, 0.0)
                launch(item["cmd"])
            else:
                self.last_click = (idx, now)
            return True
        if ev.button == 3:
            self._popup_item_menu(ev, item)
            return True
        return False

    def _on_bg_click(self, _w, ev):
        self.selected_idx = -1
        self._update_sel()
        if ev.button == 3:
            self._popup_desktop_menu(ev)
            return True
        return False

    def _add_mi(self, menu, text, cb=None, sensitive=True):
        mi = Gtk.MenuItem(label=text)
        mi.set_sensitive(sensitive)
        if cb:
            mi.connect("activate", lambda *_: cb())
        menu.append(mi)

    def _popup_item_menu(self, ev, item):
        m = Gtk.Menu()
        self._add_mi(m, "Open", lambda: launch(item["cmd"]))
        if item["kind"] == "trash":
            self._add_mi(m, "Empty Recycle Bin", lambda: empty_recycle_bin(self.rebuild), sensitive=trash_has_items())
        m.append(Gtk.SeparatorMenuItem())
        self._add_mi(m, "Properties", lambda: launch("/home/carsten/.local/bin/xp-display-properties"))
        m.show_all()
        self.active_menu = m
        m.popup_at_pointer(ev)

    def _popup_desktop_menu(self, ev):
        m = Gtk.Menu()
        self._add_mi(m, "Refresh", self.rebuild)
        m.append(Gtk.SeparatorMenuItem())
        self._add_mi(m, "Open File Manager (My Computer)", lambda: launch("thunar"))
        self._add_mi(m, "Open Command Prompt", lambda: launch("ghostty"))
        m.append(Gtk.SeparatorMenuItem())
        self._add_mi(m, "Run...", lambda: launch("/home/carsten/.local/bin/xp-run"))
        self._add_mi(m, "Task Manager", lambda: launch("/home/carsten/.local/bin/xp-taskmgr"))
        self._add_mi(m, "Control Panel", lambda: launch("/home/carsten/.local/bin/xp-control-panel"))
        m.append(Gtk.SeparatorMenuItem())
        self._add_mi(m, "Properties", lambda: launch("/home/carsten/.local/bin/xp-display-properties"))
        m.show_all()
        self.active_menu = m
        m.popup_at_pointer(ev)


def main():
    lock_fd = open(LOCK_PATH, "w")
    try:
        fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        sys.exit(0)
    win = XPDesktop()
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()
