"""
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 = 125
LOGOUT_BUTTON_MARGIN = 10

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 SoreausMenu(panorama_panel.Applet):
    name = "Soreau's menu"
    description = "Flowbox app menu"

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

        self.button = Gtk.MenuButton()

        self.menu_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        image = Gtk.Image.new_from_icon_name("wayfire")
        image.set_icon_size(Gtk.IconSize.LARGE)
        self.append(self.button)
        self.button.set_child(image)
        self.popover = Gtk.Popover()
        self.popover.set_parent(self)
        self.flowbox = Gtk.FlowBox()
        self.flowbox_item_focus_signal = self.flowbox.connect("selected-children-changed", self.on_flowbox_item_focus)
        self.populate_menu_entries()
        self.scrolled_window = Gtk.ScrolledWindow()
        self.scrolled_window.set_size_request(-1, 350)
        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(5)
        self.logout_button.set_margin_bottom(5)
        self.logout_button.set_margin_start(5)
        self.logout_button.set_margin_end(5)
        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.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(300, 400)
        self.popover.connect("show", self.on_popover_popup)
        self.button.set_popover(self.popover)
        self.logout_ui = WayfireLogoutUI()

    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 on_popover_popup(self, parent):
        for child in self.flowbox.get_selected_children():
            self.flowbox.unselect_child(child)
        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_infos = Gio.AppInfo.get_all() # Get all registered applications

        for app_info in app_infos:
            app_categories = app_info.get_categories()
            if app_categories == None:
                continue
            app_name = app_info.get_display_name()
            app_button = Gtk.Button()
            app_button.command = app_info.get_executable()
            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)

            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)
