#!/usr/bin/env python3
#
# Copyright (c) 2024 Stormux
# Copyright (c) 2010-2012 The Orca Team
# Copyright (c) 2012 Igalia, S.L.
# Copyright (c) 2005-2010 Sun Microsystems Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA  02110-1301 USA.
#
# Forked from Orca screen reader.
# Cthulhu project: https://git.stormux.org/storm/cthulhu

"""Module for performing accessible actions via a list"""

from __future__ import annotations

__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2023 Igalia, S.L."
__license__   = "LGPL"

import time
from typing import TYPE_CHECKING, Union

import gi

gi.require_version("Gdk", "3.0")
gi.require_version("Gtk", "3.0")
from gi.repository import Gdk, GLib, Gtk

from . import cmdnames
from . import dbus_service
from . import debug
from . import focus_manager
from . import guilabels
from . import input_event
from . import keybindings
from . import messages
from . import cthulhu_state
from . import script_manager
from .ax_object import AXObject
from .ax_utilities import AXUtilities

if TYPE_CHECKING:
    from . import script


class ActionList(Gtk.Window):
    """Window containing a list of accessible actions."""

    def __init__(self, presenter: ActionPresenter):
        super().__init__(window_position=Gtk.WindowPosition.MOUSE, transient_for=None)
        self._presenter = presenter
        self._setup_gui()

    def _setup_gui(self) -> None:
        """Sets up the GUI for the actions list."""

        self.set_title(guilabels.KB_GROUP_ACTIONS)
        self.set_decorated(False)

        self._listbox = Gtk.ListBox()
        self._listbox.set_selection_mode(Gtk.SelectionMode.SINGLE)
        self._listbox.connect("row-activated", self._on_row_activated)
        self._listbox.set_margin_top(5)
        self._listbox.set_margin_bottom(5)
        self.add(self._listbox)

        self.connect("key-press-event", self._on_key_press)
        self.connect("destroy", self._on_destroy)

    def _on_key_press(self, widget, event) -> bool:
        """Handles key press events."""
        
        if event.keyval == Gdk.KEY_Escape:
            self.destroy()
            return True
        return False

    def _on_row_activated(self, listbox, row) -> None:
        """Handles row activation (Enter or double-click)."""

        action_name = getattr(row, "_action_name", None)
        if action_name:
            self._presenter._perform_action(action_name)

    def _on_destroy(self, widget) -> None:
        """Handles window destruction."""

        GLib.idle_add(self._presenter._clear_gui_and_restore_focus)

    def populate_actions(self, actions: Union[dict[str, str], list[str]]) -> None:
        """Populates the list with accessible actions."""

        if isinstance(actions, dict):
            items = list(actions.items())
        else:
            items = [(action, action) for action in actions]

        # Clear existing items
        for child in self._listbox.get_children():
            self._listbox.remove(child)

        # Add actions to list
        for action_name, label_text in items:
            row = Gtk.ListBoxRow()
            label = Gtk.Label(label=label_text, xalign=0)
            label.set_margin_start(10)
            label.set_margin_end(10)
            row.add(label)
            setattr(row, "_action_name", action_name)
            self._listbox.add(row)

        # Select first item
        if actions:
            first_row = self._listbox.get_row_at_index(0)
            if first_row:
                self._listbox.select_row(first_row)
                first_row.grab_focus()

    def show_gui(self) -> None:
        """Shows the window."""

        self.show_all()
        self.present_with_time(time.time())
        self._listbox.grab_focus()


class ActionPresenter:
    """Provides a list for performing accessible actions on an object."""

    def __init__(self):
        self._handlers = None
        self._bindings = None
        self._gui = None
        self._obj = None
        self._window = None
        
        # Initialize handlers
        self._handlers = self.get_handlers(True)
        # _bindings will be initialized lazily in get_bindings()

        msg = "ACTION PRESENTER: Registering D-Bus commands."
        debug.printMessage(debug.LEVEL_INFO, msg, True)
        controller = dbus_service.get_remote_controller()
        controller.register_decorated_module("ActionPresenter", self)

    def get_handlers(self, refresh: bool = False) -> dict:
        """Returns a dictionary of input event handlers."""

        if self._handlers is None or refresh:
            msg = "ACTION PRESENTER: Getting input event handlers."
            debug.printMessage(debug.LEVEL_INFO, msg, True)
            self._setup_handlers()

        return self._handlers

    def get_bindings(self, refresh: bool = False, is_desktop: bool = True) -> keybindings.KeyBindings:
        """Returns keybindings for this presenter."""

        if self._bindings is None or refresh:
            msg = "ACTION PRESENTER: Getting key bindings."
            debug.printMessage(debug.LEVEL_INFO, msg, True)
            self._setup_bindings()

        return self._bindings

    def _setup_handlers(self) -> None:
        """Sets up input event handlers for this presenter."""

        msg = "ACTION PRESENTER: Setting up handlers."
        debug.printMessage(debug.LEVEL_INFO, msg, True)

        self._handlers = {}

        self._handlers["show_actions_list"] = \
            input_event.InputEventHandler(
                self.show_actions_list,
                cmdnames.SHOW_ACTIONS_LIST)

        msg = "ACTION PRESENTER: Handlers set up."
        debug.printMessage(debug.LEVEL_INFO, msg, True)

    def _setup_bindings(self) -> None:
        """Sets up key bindings for this presenter."""

        msg = "ACTION PRESENTER: Setting up bindings."
        debug.printMessage(debug.LEVEL_INFO, msg, True)

        self._bindings = keybindings.KeyBindings()
        self._bindings.add(keybindings.KeyBinding(
                "a",
                keybindings.defaultModifierMask,
                keybindings.CTHULHU_SHIFT_MODIFIER_MASK,
                self._handlers["show_actions_list"]))

        msg = "ACTION PRESENTER: Bindings set up."
        debug.printMessage(debug.LEVEL_INFO, msg, True)

    def _restore_focus(self) -> None:
        """Restores focus to the object associated with the actions list."""

        tokens = ["ACTION PRESENTER: Restoring focus to", self._obj, "in", self._window]
        debug.printTokens(debug.LEVEL_INFO, tokens, True)

        reason = "Action Presenter list is being destroyed"
        app = AXObject.get_application(self._obj)
        script = script_manager.get_manager().get_script(app, self._obj)
        script_manager.get_manager().set_active_script(script, reason)

        manager = focus_manager.get_manager()
        manager.clear_state(reason)
        manager.set_active_window(self._window)
        manager.set_locus_of_focus(None, self._obj)

    def _present_message(self, script, full_message, brief_message=None, notify_user=True) -> None:
        """Presents a message using the provided script or the active script."""

        if not notify_user:
            return

        if script is not None:
            script.presentMessage(full_message, brief_message)
            return

        active_script = cthulhu_state.activeScript
        if active_script is not None:
            active_script.presentMessage(full_message, brief_message)
            return

        msg = "ACTION PRESENTER: Unable to present message (no script)."
        debug.printMessage(debug.LEVEL_INFO, msg, True)

    def _clear_gui_and_restore_focus(self) -> None:
        """Clears the GUI reference and then restores focus."""

        self._gui = None
        GLib.timeout_add(150, self._maybe_restore_focus)

    def _maybe_restore_focus(self) -> bool:
        """Restores focus unless it already moved to another object in the target app."""

        if not AXObject.is_valid(self._obj):
            return False

        manager = focus_manager.get_manager()
        current_focus = manager.get_locus_of_focus()
        if current_focus and AXObject.is_valid(current_focus):
            target_app = AXObject.get_application(self._obj)
            focus_app = AXObject.get_application(current_focus)
            if target_app and focus_app == target_app and current_focus != self._obj:
                tokens = ["ACTION PRESENTER: Skipping focus restore; focus now on", current_focus]
                debug.printTokens(debug.LEVEL_INFO, tokens, True)
                return False

        self._restore_focus()
        return False

    def _perform_action(self, action: str) -> None:
        """Attempts to perform the named action."""

        if self._gui is None:
            msg = "ACTION PRESENTER: _perform_action called when self._gui is None."
            debug.printMessage(debug.LEVEL_INFO, msg, True)
            return

        self._gui.hide()
        result = AXObject.do_named_action(self._obj, action)
        tokens = ["ACTION PRESENTER: Performing", action, "on", self._obj, "succeeded:", result]
        debug.printTokens(debug.LEVEL_INFO, tokens, True)
        
        # Use idle_add for asynchronous destruction to allow action to complete
        GLib.idle_add(self._gui.destroy)

    def present_with_time(self, obj, start_time: float, script=None, notify_user=True) -> bool:
        """Presents accessible actions for the given object with timing."""

        try:
            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: present_with_time called with obj: {obj}", True)

            if self._gui is not None:
                msg = "ACTION PRESENTER: GUI already exists."
                debug.printMessage(debug.LEVEL_INFO, msg, True)
                return False

            if obj is None:
                msg = "ACTION PRESENTER: No object found, presenting LOCATION_NOT_FOUND"
                debug.printMessage(debug.LEVEL_INFO, msg, True)
                full_message = messages.LOCATION_NOT_FOUND_FULL
                brief_message = messages.LOCATION_NOT_FOUND_BRIEF
                self._present_message(script, full_message, brief_message, notify_user)
                return True

            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: Getting actions for object: {obj}", True)
            actions = {}
            for i in range(AXObject.get_n_actions(obj)):
                name = AXObject.get_action_name(obj, i)
                if not name:
                    continue
                localized_name = AXObject.get_action_localized_name(obj, i)
                description = AXObject.get_action_description(obj, i)
                actions[name] = localized_name or description or name

            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: Found {len(actions)} actions: {actions}", True)
            
            if not actions:
                msg = "ACTION PRESENTER: No actions found, presenting NO_ACTIONS_FOUND_ON"
                debug.printMessage(debug.LEVEL_INFO, msg, True)
                name = AXObject.get_name(obj) or AXUtilities.get_localized_role_name(obj)
                full_message = messages.NO_ACTIONS_FOUND_ON % name
                self._present_message(script, full_message, notify_user=notify_user)
                return True

            debug.printMessage(debug.LEVEL_INFO, "ACTION PRESENTER: Creating GUI", True)
            self._obj = obj
            self._window = focus_manager.get_manager().get_active_window()

            self._gui = ActionList(self)
            self._gui.populate_actions(actions)
            self._gui.show_gui()

            debug.printMessage(debug.LEVEL_INFO, "ACTION PRESENTER: GUI created successfully", True)
            return True
        except Exception as e:
            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: ERROR in present_with_time: {e}", True)
            import traceback
            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: Traceback: {traceback.format_exc()}", True)
            return False

    @dbus_service.command
    def show_actions_list(
        self,
        script: script.Script = None,
        input_event: input_event.InputEvent = None,
        notify_user: bool = True
    ) -> bool:
        """Shows the accessible actions list."""

        try:
            msg = f"ACTION PRESENTER: show_actions_list called! input_event: {input_event}"
            debug.printMessage(debug.LEVEL_INFO, msg, True)

            start_time = time.time()

            obj = None
            if input_event is not None:
                obj = input_event.get_object()
            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: Object from input_event: {obj}", True)

            if obj is None:
                manager = focus_manager.get_manager()
                _mode, obj = manager.get_active_mode_and_object_of_interest()
                if obj is None:
                    obj = manager.get_locus_of_focus()

            result = self.present_with_time(obj, start_time, script, notify_user)
            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: show_actions_list returning: {result}", True)
            return result
        except Exception as e:
            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: ERROR in show_actions_list: {e}", True)
            import traceback
            debug.printMessage(debug.LEVEL_INFO, f"ACTION PRESENTER: Traceback: {traceback.format_exc()}", True)
            return False


_presenter = ActionPresenter()

def getPresenter() -> ActionPresenter:
    """Returns the Action Presenter singleton."""
    return _presenter
