#!/usr/bin/env python3
"""Native Windows XP Control Panel with Luna Task Sidebar + Sounds/User/Power applets."""

import os
import platform
import shutil
import subprocess
import sys
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")
from gi.repository import Gtk, Gdk, GdkPixbuf, Pango

LUNA_32 = "/usr/local/share/icons/luna/32x32"
MUTE_FLAG = Path("/home/carsten/.config/hypr/mute-xp-sounds")
SOUND_DIR = Path("/usr/local/share/sounds/Windows XP Default/stereo/res")
USERPICS_DIR = Path("/usr/local/share/wintc/userpics")
USERPIC_DEST = Path("/home/carsten/.config/hypr/assets/userpic.png")

CP_CSS = b"""
.xp-cp-sidebar {
    background-image: linear-gradient(180deg, #7BA2E7 0%, #6375D6 100%);
    padding: 12px 10px;
}
.xp-cp-card {
    background-color: #D6DFF7;
    border: 1px solid #FFFFFF;
    border-radius: 3px;
}
.xp-cp-card-hdr {
    background-image: linear-gradient(90deg, #FFFFFF 0%, #C6D3F7 100%);
    color: #215DC6;
    font-family: "Tahoma", sans-serif;
    font-weight: bold;
    font-size: 8.5pt;
    padding: 4px 10px;
    border-radius: 3px 3px 0 0;
}
.xp-cp-card-body {
    padding: 8px 10px;
}
.xp-cp-link {
    background: transparent;
    background-image: none;
    border: none;
    border-image-source: none;
    box-shadow: none;
    color: #215DC6;
    font-family: "Tahoma", sans-serif;
    font-size: 8.5pt;
    padding: 2px 0px;
}
.xp-cp-link:hover {
    color: #428EFF;
    text-decoration: underline;
    background: transparent;
    border-image-source: none;
}
.xp-cp-main {
    background-color: #FFFFFF;
    padding: 14px 16px;
}
.xp-cp-tile {
    background: transparent;
    background-image: none;
    border: 1px solid transparent;
    border-image-source: none;
    box-shadow: none;
    padding: 8px 6px;
    border-radius: 3px;
}
.xp-cp-tile:hover {
    background-color: #E8F1FD;
    border-color: #99BFE8;
    border-image-source: none;
}
.xp-cp-tile-title {
    font-family: "Tahoma", sans-serif;
    font-size: 8.5pt;
    font-weight: bold;
    color: #000000;
}
.xp-cp-tile-desc {
    font-family: "Tahoma", sans-serif;
    font-size: 8pt;
    color: #555555;
}
"""


def load_luna_icon(rel_path, size=32):
    p = os.path.join(LUNA_32, rel_path)
    if os.path.exists(p):
        try:
            pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(p, size, size, True)
            return Gtk.Image.new_from_pixbuf(pb)
        except Exception:
            pass
    return Gtk.Image.new_from_icon_name("preferences-system", Gtk.IconSize.DND)


def open_sounds_dialog(parent=None):
    dlg = Gtk.Dialog(title="Sounds and Audio Devices Properties", transient_for=parent)
    dlg.set_default_size(390, 340)
    dlg.set_resizable(False)
    area = dlg.get_content_area()
    area.set_border_width(12)
    area.set_spacing(10)

    mute_cb = Gtk.CheckButton(label="Enable Windows XP system event sounds")
    mute_cb.set_active(not MUTE_FLAG.exists())
    area.pack_start(mute_cb, False, False, 0)

    lbl = Gtk.Label(label="Program events (select a sound and click Test):")
    lbl.set_xalign(0.0)
    area.pack_start(lbl, False, False, 0)

    sw = Gtk.ScrolledWindow()
    sw.set_shadow_type(Gtk.ShadowType.IN)
    sw.set_size_request(-1, 175)
    store = Gtk.ListStore(str, str)
    for wav in sorted(SOUND_DIR.glob("*.wav")):
        store.append([wav.stem.replace("-", " ").title(), str(wav)])
    tv = Gtk.TreeView(model=store)
    tv.set_headers_visible(False)
    tv.append_column(Gtk.TreeViewColumn("Sound", Gtk.CellRendererText(), text=0))
    sw.add(tv)
    area.pack_start(sw, True, True, 0)

    row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
    play_btn = Gtk.Button.new_with_label("Test Sound")
    def on_play(_b):
        model, it = tv.get_selection().get_selected()
        if it:
            subprocess.Popen(["paplay", model[it][1]], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    play_btn.connect("clicked", on_play)
    row.pack_start(play_btn, False, False, 0)

    mixer_btn = Gtk.Button.new_with_label("Open Volume Mixer...")
    mixer_btn.connect("clicked", lambda *_: subprocess.Popen(["hyprctl", "dispatch", "exec", "pavucontrol"],
                                                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
    row.pack_end(mixer_btn, False, False, 0)
    area.pack_start(row, False, False, 0)

    dlg.add_buttons("OK", Gtk.ResponseType.OK, "Cancel", Gtk.ResponseType.CANCEL)
    dlg.show_all()
    if dlg.run() == Gtk.ResponseType.OK:
        if mute_cb.get_active():
            MUTE_FLAG.unlink(missing_ok=True)
        else:
            MUTE_FLAG.touch()
    dlg.destroy()


def open_user_accounts_dialog(parent=None):
    dlg = Gtk.Dialog(title="User Accounts — Change Picture", transient_for=parent)
    dlg.set_default_size(440, 360)
    area = dlg.get_content_area()
    area.set_border_width(12)
    area.set_spacing(8)

    area.pack_start(Gtk.Label(label="Pick a new picture for your Start Menu and Lock Screen:", xalign=0), False, False, 0)

    sw = Gtk.ScrolledWindow()
    sw.set_shadow_type(Gtk.ShadowType.IN)
    fb = Gtk.FlowBox()
    fb.set_max_children_per_line(6)
    fb.set_selection_mode(Gtk.SelectionMode.SINGLE)
    fb.set_row_spacing(6)
    fb.set_column_spacing(6)
    fb.set_border_width(8)

    pics = sorted(USERPICS_DIR.glob("*.png")) if USERPICS_DIR.exists() else []
    for p in pics:
        pb = GdkPixbuf.Pixbuf.new_from_file_at_scale(str(p), 48, 48, True)
        img = Gtk.Image.new_from_pixbuf(pb)
        img.set_tooltip_text(p.stem)
        child = Gtk.FlowBoxChild()
        child.pic_path = str(p)
        child.add(img)
        fb.add(child)

    sw.add(fb)
    area.pack_start(sw, True, True, 0)

    dlg.add_buttons("Change Picture", Gtk.ResponseType.OK, "Cancel", Gtk.ResponseType.CANCEL)
    dlg.show_all()
    if dlg.run() == Gtk.ResponseType.OK:
        sel = fb.get_selected_children()
        if sel:
            chosen = sel[0].pic_path
            shutil.copyfile(chosen, USERPIC_DEST)
            # Also update xp-generate-logon-bg & regenerate lockscreen
            gen = Path("/home/carsten/.local/bin/xp-generate-logon-bg")
            if gen.exists():
                txt = gen.read_text(encoding="utf-8")
                import re
                txt = re.sub(r'pic_path = ".*?"', f'pic_path = "{chosen}"', txt, count=1)
                gen.write_text(txt, encoding="utf-8")
                subprocess.Popen([str(gen)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            subprocess.Popen(["pkill", "-HUP", "-f", "xp-start-menu"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    dlg.destroy()


def open_system_props_dialog(parent=None):
    dlg = Gtk.Dialog(title="System Properties", transient_for=parent)
    dlg.set_default_size(390, 290)
    dlg.set_resizable(False)
    area = dlg.get_content_area()
    area.set_border_width(14)
    area.set_spacing(10)

    # Read CPU & RAM
    cpu = "Intel Processor"
    try:
        for line in Path("/proc/cpuinfo").read_text().splitlines():
            if line.startswith("model name"):
                cpu = line.split(":", 1)[1].strip()
                break
    except Exception:
        pass
    mem_gb = "?"
    try:
        for line in Path("/proc/meminfo").read_text().splitlines():
            if line.startswith("MemTotal:"):
                kb = int(line.split()[1])
                mem_gb = f"{kb / (1024*1024):.1f} GB of RAM"
                break
    except Exception:
        pass

    row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=16)
    row.pack_start(load_luna_icon("devices/system.png", 48), False, False, 4)
    info = Gtk.Label(
        label=(
            f"System:\n"
            f"  Microsoft Windows XP (Hyprland Edition)\n"
            f"  Ubuntu 26.04 LTS — Kernel {platform.release()}\n\n"
            f"Registered to:\n"
            f"  {os.environ.get('USER', 'carsten')}\n\n"
            f"Computer:\n"
            f"  {cpu}\n"
            f"  {mem_gb}"
        )
    )
    info.set_xalign(0.0)
    info.set_line_wrap(True)
    row.pack_start(info, True, True, 0)
    area.pack_start(row, True, True, 0)
    dlg.add_buttons("OK", Gtk.ResponseType.OK)
    dlg.show_all()
    dlg.run()
    dlg.destroy()


class XPControlPanel(Gtk.Window):
    def __init__(self):
        super().__init__(title="Control Panel")
        self.set_wmclass("xp-control-panel", "xp-control-panel")
        self.set_default_size(740, 480)

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

        root = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=0)
        self.add(root)

        # Left Luna Task Sidebar
        sidebar = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12)
        sidebar.set_size_request(198, -1)
        sidebar.get_style_context().add_class("xp-cp-sidebar")

        sidebar.pack_start(self._make_card("Control Panel", [
            ("Display Properties", lambda: self._launch("/home/carsten/.local/bin/xp-display-properties")),
            ("Change Wallpaper", lambda: self._launch("/home/carsten/.local/bin/xp-display-properties --desktop")),
            ("Sounds and Audio", lambda: open_sounds_dialog(self)),
            ("User Account Picture", lambda: open_user_accounts_dialog(self)),
        ]), False, False, 0)

        sidebar.pack_start(self._make_card("See Also", [
            ("Windows Task Manager", lambda: self._launch("/home/carsten/.local/bin/xp-taskmgr")),
            ("Run Command...", lambda: self._launch("/home/carsten/.local/bin/xp-run")),
            ("System Information", lambda: open_system_props_dialog(self)),
        ]), False, False, 0)

        root.pack_start(sidebar, False, False, 0)

        # Right White Main Applet Grid
        sw = Gtk.ScrolledWindow()
        sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)

        main_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        main_box.get_style_context().add_class("xp-cp-main")

        fb = Gtk.FlowBox()
        fb.set_valign(Gtk.Align.START)
        fb.set_max_children_per_line(3)
        fb.set_min_children_per_line(2)
        fb.set_selection_mode(Gtk.SelectionMode.NONE)
        fb.set_row_spacing(10)
        fb.set_column_spacing(12)
        fb.set_homogeneous(True)

        applets = [
            ("apps/preferences-desktop-display.png", "Display", "Themes, wallpaper & cursors",
             lambda: self._launch("/home/carsten/.local/bin/xp-display-properties")),
            ("devices/audio-speakers.png", "Sounds and Audio", "XP sounds & volume mixer",
             lambda: open_sounds_dialog(self)),
            ("apps/preferences-system-network.png", "Network Connections", "Wi-Fi, Ethernet & VPN",
             lambda: self._launch("nm-connection-editor")),
            ("apps/preferences-desktop-peripherals.png", "Bluetooth Devices", "Pair & manage Bluetooth",
             lambda: self._launch("blueman-manager")),
            ("devices/video-display.png", "Monitor Layout", "Resolution & displays",
             lambda: self._launch("nwg-displays")),
            ("apps/preferences-desktop-personal.png", "User Accounts", "Change user picture",
             lambda: open_user_accounts_dialog(self)),
            ("apps/preferences-system.png", "Task Manager", "Apps, processes & CPU",
             lambda: self._launch("/home/carsten/.local/bin/xp-taskmgr")),
            ("devices/system.png", "System", "Hardware & OS info",
             lambda: open_system_props_dialog(self)),
            ("apps/preferences-desktop-theme.png", "Date and Time", "Clock & calendar",
             lambda: self._launch("/home/carsten/.local/bin/xp-calendar-popup")),
            ("apps/preferences-other.png", "GTK Look & Feel", "Advanced widget settings",
             lambda: self._launch("nwg-look")),
            ("apps/preferences-desktop-font.png", "Qt6 Appearance", "Qt app theme & fonts",
             lambda: self._launch("qt6ct")),
            ("actions/system-run.png", "Run...", "Launch a command",
             lambda: self._launch("/home/carsten/.local/bin/xp-run")),
        ]

        for icon_rel, title, desc, cb in applets:
            btn = Gtk.Button()
            btn.get_style_context().add_class("xp-cp-tile")
            row = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10)
            row.pack_start(load_luna_icon(icon_rel, 32), False, False, 0)
            col = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=2)
            col.set_valign(Gtk.Align.CENTER)
            t_lbl = Gtk.Label(label=title, xalign=0)
            t_lbl.get_style_context().add_class("xp-cp-tile-title")
            d_lbl = Gtk.Label(label=desc, xalign=0)
            d_lbl.set_ellipsize(Pango.EllipsizeMode.END)
            d_lbl.get_style_context().add_class("xp-cp-tile-desc")
            col.pack_start(t_lbl, False, False, 0)
            col.pack_start(d_lbl, False, False, 0)
            row.pack_start(col, True, True, 0)
            btn.add(row)
            btn.connect("clicked", lambda _b, fn=cb: fn())
            fb.add(btn)

        main_box.pack_start(fb, True, True, 0)
        sw.add(main_box)
        root.pack_start(sw, True, True, 0)

        self.connect("key-press-event", lambda _w, ev: Gtk.main_quit() if ev.keyval == Gdk.KEY_Escape else False)
        self.connect("destroy", Gtk.main_quit)

    def _make_card(self, title, links):
        card = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        card.get_style_context().add_class("xp-cp-card")
        hdr = Gtk.Label(label=title, xalign=0)
        hdr.get_style_context().add_class("xp-cp-card-hdr")
        card.pack_start(hdr, False, False, 0)

        body = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=3)
        body.get_style_context().add_class("xp-cp-card-body")
        for text, cb in links:
            b = Gtk.Button()
            b.get_style_context().add_class("xp-cp-link")
            lbl = Gtk.Label(label=text, xalign=0)
            b.add(lbl)
            b.connect("clicked", lambda _b, fn=cb: fn())
            body.pack_start(b, False, False, 0)
        card.pack_start(body, False, False, 0)
        return card

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


def main():
    if "--sounds" in sys.argv:
        open_sounds_dialog()
        return
    if "--users" in sys.argv:
        open_user_accounts_dialog()
        return
    win = XPControlPanel()
    win.show_all()
    Gtk.main()


if __name__ == "__main__":
    main()
