import os
from pathlib import Path
import wayfire
import panorama_panel

import gi
from wayfire import WayfireSocket

gi.require_version("Gtk", "4.0")

from gi.repository import Gtk, GLib, Gio, Gdk


module_directory = Path(__file__).resolve().parent


"""
@Gtk.Template(filename=str(module_directory / "panorama-clock-options.ui"))
class ClockOptions(Gtk.Window):
    __gtype_name__ = "ClockOptions"
    format_entry: Gtk.Entry = Gtk.Template.Child()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.connect("close-request", lambda *args: self.destroy())
"""


class WindowButton(Gtk.ToggleButton):
    def __init__(self, window_id, window_title, **kwargs):
        super().__init__(**kwargs)

        self.window_id = window_id
        self.window_title = window_title
        self.set_has_frame(False)

        self.set_label(self.window_title)


class WFWindowList(panorama_panel.Applet):
    name = "Wayfire window list"
    description = "Traditional window list (for Wayfire)"

    def __init__(self, orientation=Gtk.Orientation.HORIZONTAL, config=None):
        super().__init__(orientation=orientation, config=config)
        if config is None:
            config = {}

        self.socket = WayfireSocket()
        self.socket.watch()
        fd = self.socket.client.fileno()
        GLib.io_add_watch(fd, GLib.IO_IN, self.on_wf_event)

        self.initial_button = Gtk.ToggleButton()

        self.window_buttons: dict[int, WindowButton] = {}

        for view in self.socket.list_views():
            self.create_window_button(view)

        self.context_menu = self.make_context_menu()
        panorama_panel.track_popover(self.context_menu)

        right_click_controller = Gtk.GestureClick()
        right_click_controller.set_button(3)
        right_click_controller.connect("pressed", self.show_context_menu)

        self.add_controller(right_click_controller)

        action_group = Gio.SimpleActionGroup()
        options_action = Gio.SimpleAction.new("options", None)
        options_action.connect("activate", self.show_options)
        action_group.add_action(options_action)
        self.insert_action_group("applet", action_group)

        self.options_window = None

    def create_window_button(self, view):
        button = WindowButton(view["id"], view["title"])
        button.set_group(self.initial_button)

        self.window_buttons[view["id"]] = button
        self.append(button)

    def remove_window_button(self, view):
        self.remove(self.window_buttons[view["id"]])
        self.window_buttons[view["id"]] = None

    def focus_window_button(self, view):
        self.window_buttons[view["id"]].set_active(True)

    def on_wf_event(self, source, condition):
        if condition == GLib.IO_IN:
            try:
                message = self.socket.read_next_event()
                event = message.get("event")
                view = message.get("view", {})
                print(f"[{event}] {view.get('app-id')} - {view.get('title')}")
                match event:
                    case "view-mapped":
                        self.create_window_button(message["view"])
                    case "view-unmapped":
                        self.remove_window_button(message["view"])
                    case "view-focused":
                        self.focus_window_button(message["view"])
            except Exception as e:
                print("Error reading Wayfire event:", e)
        return True

    def make_context_menu(self):
        menu = Gio.Menu()
        menu.append("Window list _options", "applet.options")
        context_menu = Gtk.PopoverMenu.new_from_model(menu)
        context_menu.set_has_arrow(False)
        context_menu.set_parent(self)
        context_menu.set_halign(Gtk.Align.START)
        context_menu.set_flags(Gtk.PopoverMenuFlags.NESTED)
        return context_menu

    def show_context_menu(self, gesture, n_presses, x, y):
        rect = Gdk.Rectangle()
        rect.x = int(x)
        rect.y = int(y)
        rect.width = 1
        rect.height = 1

        self.context_menu.set_pointing_to(rect)
        self.context_menu.popup()

    def show_options(self, _0=None, _1=None):
        """
        if self.options_window is None:
            self.options_window = ClockOptions()
            self.options_window.format_entry.set_text(self.formatting)
            self.options_window.format_entry.connect("changed", self.update_formatting)

            def reset_window(*args):
                self.options_window = None

            self.options_window.connect("close-request", reset_window)
        self.options_window.present()
        """

    def get_config(self):
        return {}
