# request_item.py
#
# Copyright 2025 Pavel Baksy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

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

_METHOD_CSS = {
    'GET':    'accent',
    'POST':   'success',
    'PUT':    'warning',
    'PATCH':  'warning',
    'DELETE': 'error',
}


@Gtk.Template(resource_path='/cz/bugsy/roster/widgets/request-item.ui')
class RequestItem(Gtk.Box):
    """Widget for displaying a saved request."""

    __gtype_name__ = 'RequestItem'

    method_label = Gtk.Template.Child()
    name_label = Gtk.Template.Child()
    menu_button = Gtk.Template.Child()

    __gsignals__ = {
        'load-requested': (GObject.SIGNAL_RUN_FIRST, None, ()),
        'delete-requested': (GObject.SIGNAL_RUN_FIRST, None, ()),
        'move-up-requested': (GObject.SIGNAL_RUN_FIRST, None, ()),
        'move-down-requested': (GObject.SIGNAL_RUN_FIRST, None, ()),
        'move-to-project-requested': (GObject.SIGNAL_RUN_FIRST, None, (GObject.TYPE_STRING,)),
    }

    def __init__(self, saved_request):
        super().__init__()
        self.saved_request = saved_request
        method = saved_request.request.method
        self.method_label.set_text(method)
        self.method_label.add_css_class(_METHOD_CSS.get(method, 'dim-label'))
        display_name = saved_request.name
        for prefix in _METHOD_CSS:
            if display_name.upper().startswith(prefix + ' '):
                display_name = display_name[len(prefix) + 1:]
                break
        self.name_label.set_text(display_name)

        self._setup_menu()

        # Click gesture for loading (on the whole row, but not on the menu button)
        gesture = Gtk.GestureClick.new()
        gesture.connect('released', self._on_clicked)
        self.add_controller(gesture)

    def _setup_menu(self):
        actions = Gio.SimpleActionGroup.new()

        self._move_up_action = Gio.SimpleAction.new("move-up", None)
        self._move_up_action.connect("activate", lambda *_: self.emit('move-up-requested'))
        actions.add_action(self._move_up_action)

        self._move_down_action = Gio.SimpleAction.new("move-down", None)
        self._move_down_action.connect("activate", lambda *_: self.emit('move-down-requested'))
        actions.add_action(self._move_down_action)

        move_to = Gio.SimpleAction.new("move-to-project", GLib.VariantType.new("s"))
        move_to.connect("activate", self._on_move_to_project_activated)
        actions.add_action(move_to)

        delete = Gio.SimpleAction.new("delete", None)
        delete.connect("activate", lambda *_: self.emit('delete-requested'))
        actions.add_action(delete)

        self.insert_action_group("request", actions)

        # Build menu model
        menu = Gio.Menu()

        reorder_section = Gio.Menu()
        reorder_section.append("Move Up", "request.move-up")
        reorder_section.append("Move Down", "request.move-down")
        menu.append_section(None, reorder_section)

        self._move_to_submenu = Gio.Menu()
        move_section = Gio.Menu()
        move_section.append_submenu("Move to Project", self._move_to_submenu)
        menu.append_section(None, move_section)

        delete_section = Gio.Menu()
        delete_section.append("Delete", "request.delete")
        menu.append_section(None, delete_section)

        self.menu_button.set_menu_model(menu)

    def _on_move_to_project_activated(self, action, param):
        self.emit('move-to-project-requested', param.get_string())

    def _on_clicked(self, gesture, n_press, x, y):
        """Load request on row click (but not if the menu button was clicked)."""
        # Check if the click was on the menu button — if so, ignore
        alloc = self.menu_button.get_allocation()
        if alloc.x <= x <= alloc.x + alloc.width and alloc.y <= y <= alloc.y + alloc.height:
            return
        self.emit('load-requested')

    def set_can_move_up(self, can: bool):
        self._move_up_action.set_enabled(can)

    def set_can_move_down(self, can: bool):
        self._move_down_action.set_enabled(can)

    def set_other_projects(self, projects):
        """Rebuild the 'Move to Project' submenu from the given project list."""
        self._move_to_submenu.remove_all()
        for p in projects:
            self._move_to_submenu.append(p.name, f"request.move-to-project::{p.id}")
