#!/usr/bin/env python3
"""
Translates the com.canonical.dbusmenu protocol to Gio menus.
Based on a C++ implementation.
Thanks to https://github.com/WayfireWM/wf-shell/blob/master/src/panel/widgets/tray/item.hpp
for the C++ version which is Copyright 2025, trigg <https://github.com/trigg>,
MIT/Expat Licence.
Python version: Copyright 2025, roundabout-host.com <vlad@roundabout-host.com>

This file (and no other files, unless otherwise stated) is licensed under the
MIT/Expat Licence:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import typing
import uuid

from gi.repository import GLib, Gio, GObject, Dbusmenu

class CanonicalMenuModel(GObject.Object):
    """Implements com.canonical.dbusmenu protocol.
    Provides a `menu` attribute to get a Gio.Menu for the specified DBus object, and an
    `actions` attribute that is a Gio.ActionGroup with the menu actions to insert where needed.
    """
    def __init__(self):
        """Generate a disconnected instance."""
        super().__init__()
        self.prefix = None
        self.client = None
        self.prefix = ""
        self.actions = Gio.SimpleActionGroup()
        self.menu: typing.Optional[Gio.Menu] = Gio.Menu()

    def connect_dbus(self, dbus_name: str, menu_path: str, prefix: str) -> None:
        """Connect this menu with the specified DBus object.
        :param dbus_name: The bus name to use, like ":1.360" or "org.gnome.Fractal"
        :param menu_path: The DBus path to the menu. It can be found in the Menu attribute of an
        org.kde.StatusNotifierItem.
        :param prefix: The prefix to use for action names; use this name for inserting the
        action group.
        """
        self.prefix = prefix
        self.client = Dbusmenu.Client.new(dbus_name, menu_path)
        self.client.connect("layout-updated", self._layout_updated)
        root = self.client.get_root()
        self.reconstitute(root)

    def reconstitute(self, root_item: Dbusmenu.Menuitem):
        """Regenerate the menu.
        :param root_item: The item to recursively generate from.
        """
        self.menu.remove_all()
        for action_name in self.actions.list_actions():
            self.actions.remove_action(action_name)

        self._iterate_children(self.menu, root_item, 0)

    def _iterate_children(self, parent_menu, parent, count):
        if isinstance(parent, Dbusmenu.Menuitem):
            current_section = Gio.Menu()
            for child in parent.get_children():
                label = child.property_get("label")
                if not label:
                    parent_menu.append_section(None, current_section)
                    current_section = Gio.Menu()
                    continue

                menu_type = ""
                icon_name = ""
                toggle_type = ""

                if child.property_exist("type"):
                    menu_type = child.property_get("type")
                enabled = child.property_get_bool("enabled")
                if child.property_exist("icon-name"):
                    icon_name = child.property_get("icon-name")
                toggle_state = child.property_get_int("toggle-state")
                if child.property_exist("toggle-type"):
                    icon_name = child.property_get("toggle-type")
                has_children = bool(child.get_children())

                if has_children:
                    submenu = Gio.Menu()
                    count = self._iterate_children(submenu, child, count)
                    current_section.append_submenu(label, submenu)
                else:
                    item = Gio.MenuItem.new(label, "a")
                    if enabled:
                        # Difference from C++ version: we don't use the label, to make it easier
                        # to translate
                        action_name = f"mi{count}"
                        action_string = f"{self.prefix}.{action_name}"
                        if toggle_type == "radio":
                            item.set_action_and_target_value(action_string, GLib.Variant.new_string(action_name))
                            boolean_action = Gio.SimpleAction(name=action_name, state=GLib.Variant.new_string(action_name if toggle_state else ""))

                            # A default argument is needed, otherwise the last item will be used
                            def on_activate(action, vb, item=child):
                                data = GLib.Variant.new_int32(0)
                                item.handle_event("clicked", data, 0)

                            boolean_action.connect("activate", on_activate)
                            self.actions.add_action(boolean_action)
                        elif toggle_type == "check":
                            item.set_action_and_target_value(action_string, GLib.Variant.new_boolean(toggle_state))
                            boolean_action = Gio.SimpleAction(name=action_name, state=GLib.Variant.new_boolean(toggle_state))

                            def on_activate(action, vb, item=child):
                                data = GLib.Variant.new_int32(0)
                                item.handle_event("clicked", data, 0)

                            boolean_action.connect("activate", on_activate)
                            self.actions.add_action(boolean_action)
                        else:
                            item.set_detailed_action(action_string)
                            if icon_name:
                                item.set_icon(Gio.ThemedIcon.new(icon_name))
                            action = Gio.SimpleAction(name=action_name)

                            def on_activate(action, vb, item=child):
                                data = GLib.Variant.new_int32(0)
                                item.handle_event("clicked", data, 0)

                            action.connect("activate", on_activate)
                            self.actions.add_action(action)
                    current_section.append_item(item)
                count += 1
            parent_menu.append_section(None, current_section)
        return count

    def _layout_updated(self, item):
        if self.client is None:
            return

        root = self.client.get_root()
        self.reconstitute(root)
        self.emit("menu_changed")

    @GObject.Signal
    def menu_changed(self):
        pass

