"""
The MIT License (MIT)

Copyright (c) 2025 Scott Moreau <oreaus@gmail.com>, modified by <root@roundabout-host.com>

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 os
from pathlib import Path
import locale
import panorama_panel

import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Gtk4LayerShell", "1.0")

from gi.repository import Gtk, GLib, Gtk4LayerShell, Gio, Gdk, Pango
import subprocess


LOGOUT_BUTTON_SIZE = 128
LOGOUT_BUTTON_MARGIN = 12

def create_logout_ui_button(icon_name, label_text):
    layout = Gtk.Box()
    image = Gtk.Image()
    label = Gtk.Label()
    button = Gtk.Button()
    button.set_size_request(LOGOUT_BUTTON_SIZE, LOGOUT_BUTTON_SIZE)
    image.set_from_icon_name(icon_name)
    label.set_text(label_text)
    layout.set_orientation(Gtk.Orientation.VERTICAL)
    layout.set_halign(Gtk.Align.CENTER)
    layout.append(image)
    image.set_icon_size(Gtk.IconSize.LARGE)
    image.set_vexpand(True)
    layout.append(label)
    button.set_child(layout)
    return button

class WayfireLogoutUI(Gtk.Window):

    def __init__(self):
        super().__init__()

        hbox = Gtk.CenterBox()
        main_layout = Gtk.Grid()
        suspend = create_logout_ui_button("emblem-synchronizing", "Suspend")
        suspend.connect("clicked", self.on_suspend_click)
        main_layout.attach(suspend, 0, 0, 1, 1)

        hibernate = create_logout_ui_button("weather-clear-night", "Hibernate")
        hibernate.connect("clicked", self.on_hibernate_click)
        main_layout.attach(hibernate, 1, 0, 1, 1)

        switchuser = create_logout_ui_button("system-users", "Switch User")
        switchuser.connect("clicked", self.on_switchuser_click)
        main_layout.attach(switchuser, 2, 0, 1, 1)

        logout = create_logout_ui_button("system-log-out", "Log Out")
        logout.connect("clicked", self.on_logout_click)
        main_layout.attach(logout, 0, 1, 1, 1)

        reboot = create_logout_ui_button("system-reboot", "Reboot")
        reboot.connect("clicked", self.on_reboot_click)
        main_layout.attach(reboot, 1, 1, 1, 1)

        shutdown = create_logout_ui_button("system-shutdown", "Shut Down")
        shutdown.connect("clicked", self.on_shutdown_click)
        main_layout.attach(shutdown, 2, 1, 1, 1)

        cancel_button = Gtk.Button()
        cancel_button.set_size_request(100, 50)
        cancel_button.set_label("Cancel")
        main_layout.attach(cancel_button, 1, 2, 1, 1)
        cancel_button.connect("clicked", self.on_cancel_click)

        main_layout.set_row_spacing(LOGOUT_BUTTON_MARGIN)
        main_layout.set_column_spacing(LOGOUT_BUTTON_MARGIN)
        # Make surfaces layer shell
        Gtk4LayerShell.init_for_window(self)
        Gtk4LayerShell.set_namespace(self, "com.roundabout_host.panorama.logout")
        Gtk4LayerShell.set_layer(self, Gtk4LayerShell.Layer.OVERLAY)

        Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.TOP, True)
        Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.BOTTOM, True)
        Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.LEFT, True)
        Gtk4LayerShell.set_anchor(self, Gtk4LayerShell.Edge.RIGHT, True)
        main_layout.set_valign(Gtk.Align.CENTER)
        hbox.set_center_widget(main_layout)
        hbox.set_hexpand(True)
        hbox.set_vexpand(True)
        self.set_child(hbox)
        self.get_style_context().add_class("logout")
        display = self.get_display()
        css_provider = Gtk.CssProvider()
        css_provider.load_from_data("window.logout { background-color: rgba(0, 0, 0, 0.5); }")
        Gtk.StyleContext.add_provider_for_display(display, css_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER)

    def on_suspend_click(self, button):
        GLib.spawn_command_line_async("systemctl suspend")

    def on_hibernate_click(self, button):
        GLib.spawn_command_line_async("systemctl hibernate")

    def on_switchuser_click(self, button):
        GLib.spawn_command_line_async("dm-tool switch-to-greeter")

    def on_logout_click(self, button):
        GLib.spawn_command_line_async("wayland-logout")

    def on_reboot_click(self, button):
        GLib.spawn_command_line_async("systemctl reboot")

    def on_shutdown_click(self, button):
        GLib.spawn_command_line_async("systemctl poweroff")

    def on_cancel_click(self, button):
        self.hide()

class MenuItemButton(Gtk.Button):

    def __init__(self, name, desc, exe):
        super().__init__()
        self.name = name
        self.desc = desc
        self.exe = exe

class SearchMenu(panorama_panel.Applet):
    name = "Searchable menu"
    description = "Flowbox app menu"

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

        self.button = Gtk.MenuButton()

        self.menu_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        self.image = Gtk.Image.new_from_icon_name(config.get("icon_name", "wayfire"))
        self.image.set_pixel_size(config.get("icon_size", 24))
        self.append(self.button)
        self.button.set_child(self.image)
        self.popover = Gtk.Popover()
        self.popover.set_parent(self)
        self.flowbox = Gtk.FlowBox()
        self.flowbox.set_valign(Gtk.Align.START)
        self.flowbox.set_homogeneous(True)
        self.flowbox_item_focus_signal = self.flowbox.connect("selected-children-changed", self.on_flowbox_item_focus)
        self.scrolled_window = Gtk.ScrolledWindow()
        self.scrolled_window.set_size_request(-1, config.get("height", 360))
        self.scrolled_window.set_child(self.flowbox)
        self.logout_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        self.logout_button = Gtk.Button()
        self.logout_button.set_margin_top(6)
        self.logout_button.set_margin_bottom(6)
        self.logout_button.set_margin_start(6)
        self.logout_button.set_margin_end(6)
        self.logout_button.set_child(Gtk.Image.new_from_icon_name("system-shutdown"))
        self.logout_button.connect("clicked", self.on_logout_button_clicked)
        self.logout_box.set_halign(Gtk.Align.END)
        self.logout_box.append(self.logout_button)
        self.search_entry = Gtk.SearchEntry()
        self.search_entry.connect("search-changed", self.on_search_changed)
        self.search_entry.connect("activate", self.click_first_button)
        self.menu_box.append(self.search_entry)
        self.menu_box.append(self.scrolled_window)
        self.menu_box.append(self.logout_box)
        self.popover.set_child(self.menu_box)
        self.popover.set_size_request(config.get("width", 400), -1)
        self.popover.connect("show", self.on_popover_popup)
        self.button.set_popover(self.popover)
        self.logout_ui = WayfireLogoutUI()
        self.populate_menu_entries()
        self.app_info_monitor = Gio.AppInfoMonitor.get()
        self.app_info_monitor.connect("changed", self.populate_menu_entries)

    def click_first_button(self, search_entry):
        flowbox_child = self.flowbox.get_first_child()
        if flowbox_child is not None:
            button = flowbox_child.get_first_child()
            button.emit("clicked")

    def on_search_changed(self, search_entry):
        self.flowbox.remove_all()
        text =  self.search_entry.get_text().lower()
        for button in self.cached_buttons:
            if (button.name and text in button.name.lower()) or \
               (button.desc and text in button.desc.lower()) or \
               (button.exe and text in button.exe.lower()):
                self.flowbox.append(button)

    def on_logout_button_clicked(self, button):
        self.logout_ui.present()
        self.popover.popdown()

    def on_flowbox_item_focus(self, flowbox):
        selected_children = flowbox.get_selected_children()
        if len(selected_children) >= 1:
            selected_children[0].get_child().grab_focus()

    def get_config(self):
        return {
            "width": self.popover.get_size_request()[0],
            "height": self.scrolled_window.get_size_request()[1],
            "icon_name": self.image.get_icon_name(),
            "icon_size": self.image.get_pixel_size(),
        }

    def on_popover_popup(self, parent):
        for child in self.flowbox.get_selected_children():
            self.flowbox.unselect_child(child)
        self.search_entry.set_text("")
        self.popover.popup()

    def app_button_clicked(self, app_button):
        subprocess.Popen(app_button.command, start_new_session=True)
        self.popover.popdown()

    def populate_menu_entries(self, app_info_monitor=None):
        app_infos = Gio.AppInfo.get_all()
        app_infos.sort(key=lambda app_info: app_info.get_display_name().lower())
        self.cached_buttons = []

        for app_info in app_infos:
            app_categories = app_info.get_categories()
            if app_categories == None:
                continue
            app_name = app_info.get_display_name()
            command = app_info.get_executable()
            app_button = MenuItemButton(app_name, app_info.get_description(), command)
            app_button.command = command
            app_button.set_tooltip_text(app_name)
            app_label = Gtk.Label(label=app_name)
            app_label.set_ellipsize(Pango.EllipsizeMode.END)
            app_label.set_max_width_chars(7)
            app_button_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            app_button_box.append(app_label)
            app_button.set_child(app_button_box)
            app_button.set_has_frame(False)

            image = Gtk.Image()
            image.set_icon_size(Gtk.IconSize.LARGE)
            icon = app_info.get_icon()
            if icon:
                icon_name = icon.to_string()
                if not Gtk.IconTheme.get_for_display(Gdk.Display.get_default()).has_icon(icon_name):
                    continue
                if icon_name[0] == '/':
                    image.set_from_file(icon_name)
                else:
                    image.set_from_icon_name(icon_name)
            else:
                if not Gtk.IconTheme.get_for_display(Gdk.Display.get_default()).has_icon(app_name.lower()):
                    continue
                image.set_from_icon_name(app_name.lower())

            self.flowbox.append(app_button)
            app_button.connect("clicked", self.app_button_clicked)
            app_button_box.prepend(image)
            self.cached_buttons.append(app_button)
