#!/usr/bin/env python3
#
# Copyright (c) 2024 Stormux
# Copyright 2005-2008 Sun Microsystems Inc.
# Copyright 2016-2023 Igalia, S.L.
#
# Author: Joanmarie Diggs <jdiggs@igalia.com>
#
# 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

# pylint: disable=wrong-import-position
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-public-methods

"""Module to manage the focused object, window, etc."""

# This has to be the first non-docstring line in the module to make linters happy.
from __future__ import annotations

__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2005-2008 Sun Microsystems Inc." \
                "Copyright (c) 2016-2023 Igalia, S.L."
__license__   = "LGPL"

from typing import TYPE_CHECKING, Optional, Tuple, Any

import gi
gi.require_version("Atspi", "2.0")
from gi.repository import Atspi

from . import braille
from . import cthulhu_state
from . import dbus_service
from . import debug
from . import script_manager
from .ax_object import AXObject
from .ax_table import AXTable
from .ax_text import AXText

if TYPE_CHECKING:
    from .cthulhu import Cthulhu
    from .input_event import InputEvent
    from .scripts import default

def _get_ax_utilities() -> Any:
    # Avoid circular import with ax_utilities -> ax_utilities_event -> focus_manager.
    from .ax_utilities import AXUtilities
    return AXUtilities

def _log(message: str, reason: Optional[str] = None, timestamp: bool = True, stack: bool = False) -> None:
    debug.print_log(debug.LEVEL_INFO, "FOCUS MANAGER", message, reason, timestamp, stack)

def _log_tokens(tokens: list, reason: Optional[str] = None, timestamp: bool = True, stack: bool = False) -> None:
    debug.print_log_tokens(debug.LEVEL_INFO, "FOCUS MANAGER", tokens, reason, timestamp, stack)

CARET_TRACKING = "caret-tracking"
FOCUS_TRACKING = "focus-tracking"
FLAT_REVIEW = "flat-review"
MOUSE_REVIEW = "mouse-review"
OBJECT_NAVIGATOR = "object-navigator"
SAY_ALL = "say-all"


class FocusManager:
    """Manages the focused object, window, etc."""

    def __init__(self, app: Cthulhu) -> None:
        self.app: Cthulhu = app # Store app instance
        self._window: Optional[Atspi.Accessible] = cthulhu_state.activeWindow
        self._focus: Optional[Atspi.Accessible] = cthulhu_state.locusOfFocus
        self._object_of_interest: Optional[Atspi.Accessible] = cthulhu_state.objOfInterest
        self._active_mode: Optional[str] = cthulhu_state.activeMode
        self._last_cell_coordinates: Tuple[int, int] = (-1, -1)
        self._last_cursor_position: Tuple[Optional[Atspi.Accessible], int] = (None, -1)
        self._penultimate_cursor_position: Tuple[Optional[Atspi.Accessible], int] = (None, -1)

        _log("Registering D-Bus commands.")
        controller = dbus_service.get_remote_controller()
        controller.register_decorated_module("FocusManager", self)

    def clear_state(self, reason: str = "") -> None:
        """Clears everything we're tracking."""

        _log("Clearing all state", reason)
        self._focus = None
        self._window = None
        self._object_of_interest = None
        self._active_mode = None
        cthulhu_state.locusOfFocus = None
        cthulhu_state.activeWindow = None
        cthulhu_state.objOfInterest = None
        cthulhu_state.activeMode = None

    def find_focused_object(self) -> Optional[Atspi.Accessible]:
        """Returns the focused object in the active window."""

        result = _get_ax_utilities().get_focused_object(self._window)
        _log_tokens(["Focused object in", self._window, "is", result])
        return result

    def active_window_is_cthulhu(self) -> bool:
        """Returns True if the active window belongs to Cthulhu itself."""

        app = AXObject.get_application(self._window)
        appName = (AXObject.get_name(app) or "").lower()
        return appName == "cthulhu"

    def focus_and_window_are_unknown(self) -> bool:
        """Returns True if we have no knowledge about what is focused."""

        result = self._focus is None and self._window is None
        if result:
            _log("Focus and window are unknown")

        return result

    def focus_is_dead(self) -> bool:
        """Returns True if the locus of focus is dead."""

        if not AXObject.is_dead(self._focus):
            return False

        _log("Focus is dead", "dead-focus")
        return True

    def focus_is_active_window(self) -> bool:
        """Returns True if the locus of focus is the active window."""

        if self._focus is None:
            return False

        return self._focus == self._window

    def focus_is_in_active_window(self) -> bool:
        """Returns True if the locus of focus is inside the current window."""

        return self._focus is not None and AXObject.is_ancestor(self._focus, self._window)

    def emit_region_changed(
        self, obj: Atspi.Accessible,
        start_offset: Optional[int] = None,
        end_offset: Optional[int] = None,
        mode: Optional[str] = None
    ) -> None:
        """Notifies interested clients that the current region of interest has changed."""

        if start_offset is None:
            start_offset = 0
        if end_offset is None:
            end_offset = start_offset
        if mode is None:
            mode = FOCUS_TRACKING

        if obj is not None:
            obj.emit("mode-changed::" + mode, 1, "")

        if mode != self._active_mode:
            _log_tokens(["Switching mode from", self._active_mode, "to", mode])
            self._active_mode = mode
            cthulhu_state.activeMode = mode
            if mode == FLAT_REVIEW:
                braille.setBrlapiPriority(braille.BRLAPI_PRIORITY_HIGH)
            else:
                braille.setBrlapiPriority()

        _log_tokens(["Region of interest:", obj, f"({start_offset}, {end_offset})"])
        if obj is not None:
            obj.emit("region-changed", start_offset, end_offset)

        if obj != self._object_of_interest:
            _log_tokens(["Switching object of interest from", self._object_of_interest, "to", obj])
            self._object_of_interest = obj
            cthulhu_state.objOfInterest = obj

    def in_say_all(self) -> bool:
        """Returns True if we are in say-all mode."""

        return self._active_mode == SAY_ALL

    def get_active_mode_and_object_of_interest(
        self
    ) -> Tuple[Optional[str], Optional[Atspi.Accessible]]:
        """Returns the current mode and associated object of interest"""

        _log_tokens(["Active mode:", self._active_mode, "Object of interest:", self._object_of_interest])
        return self._active_mode, self._object_of_interest

    def get_penultimate_cursor_position(self) -> Tuple[Optional[Atspi.Accessible], int]:
        """Returns the penultimate cursor position as a tuple of (object, offset)."""

        obj, offset = self._penultimate_cursor_position
        _log_tokens(["Penultimate cursor position:", obj, offset])
        return obj, offset

    def get_last_cursor_position(self) -> Tuple[Optional[Atspi.Accessible], int]:
        """Returns the last cursor position as a tuple of (object, offset)."""

        obj, offset = self._last_cursor_position
        _log_tokens(["Last cursor position:", obj, offset])
        return obj, offset

    def set_last_cursor_position(self, obj: Optional[Atspi.Accessible], offset: int) -> None:
        """Sets the last cursor position as a tuple of (object, offset)."""

        _log_tokens(["Setting last cursor position to", obj, offset])
        self._penultimate_cursor_position = self._last_cursor_position
        self._last_cursor_position = obj, offset

    def get_last_cell_coordinates(self) -> Tuple[int, int]:
        """Returns the last known cell coordinates as a tuple of (row, column)."""

        row, column = self._last_cell_coordinates
        _log(f"Last known cell coordinates: row={row}, column={column}")
        return row, column

    def set_last_cell_coordinates(self, row: int, column: int) -> None:
        """Sets the last known cell coordinates as a tuple of (row, column)."""

        _log(f"Setting last cell coordinates to row={row}, column={column}")
        self._last_cell_coordinates = row, column

    def get_locus_of_focus(self) -> Optional[Atspi.Accessible]:
        """Returns the current locus of focus (i.e. the object with visual focus)."""

        _log_tokens(["Locus of focus is", self._focus])
        return self._focus

    def set_locus_of_focus(
        self,
        event: Optional[Atspi.Event],
        obj: Optional[Atspi.Accessible],
        notify_script: bool = True,
        force: bool = False
    ) -> None:
        """Sets the locus of focus (i.e., the object with visual focus)."""

        _log_tokens(["Request to set locus of focus to", obj], stack=True)

        # We clear the cache on the locus of focus because too many apps and toolkits fail
        # to emit the correct accessibility events. We do so recursively on table cells
        # to handle bugs like https://gitlab.gnome.org/GNOME/nautilus/-/issues/3253.
        recursive = _get_ax_utilities().is_table_cell(obj)
        AXObject.clear_cache(obj, recursive, "Setting locus of focus.")
        if not force and obj == self._focus:
            _log("Setting locus of focus to existing locus of focus", "no-change")
            return

        # We save the current row and column of a newly focused or selected table cell so that on
        # subsequent cell focus/selection we only present the changed location.
        row, column = AXTable.get_cell_coordinates(obj, find_cell=True)
        self.set_last_cell_coordinates(row, column)

        # We save the offset for text objects because some apps and toolkits emit caret-moved events
        # immediately after a text object gains focus, even though the caret has not actually moved.
        # TODO - JD: We should consider making this part of `save_object_info_for_events()` for the
        # motivation described above. However, we need to audit callers that set/get the position
        # before doing so.
        self.set_last_cursor_position(obj, AXText.get_caret_offset(obj))
        AXText.update_cached_selected_text(obj)

        # We save additional information about the object for events that were received at the same
        # time as the prioritized focus-change event so we don't double-present aspects about obj.
        _get_ax_utilities().save_object_info_for_events(obj)

        # TODO - JD: Consider always updating the active script here.
        script = self.app.scriptManager.get_active_script()
        if event and (script and not script.app):
            app = _get_ax_utilities().get_application(event.source)
            script = self.app.scriptManager.get_script(app, event.source)
            self.app.scriptManager.activate_script_for_context(app, event.source, "focus: locus-of-focus")

        old_focus = self._focus
        if AXObject.is_dead(old_focus):
            old_focus = None

        if obj is None:
            _log("New locus of focus is null (being cleared)", "clearing")
            self._focus = None
            cthulhu_state.locusOfFocus = None
            return

        if AXObject.is_dead(obj):
            _log_tokens(["New locus of focus", obj, "is dead. Not updating."], "dead")
            return

        if script is not None:
            if not AXObject.is_valid(obj):
                _log_tokens(["New locus of focus", obj, "is invalid. Not updating."], "invalid")
                return

        _log_tokens(["Changing locus of focus from", old_focus, "to", obj, ". Notify:", notify_script])
        self._focus = obj
        cthulhu_state.locusOfFocus = obj

        if not notify_script:
            return

        if script is None:
            _log("Cannot notify active script because there isn't one", "no-active-script")
            return

        self.emit_region_changed(obj, mode=FOCUS_TRACKING)
        script.locus_of_focus_changed(event, old_focus, self._focus)

    def active_window_is_active(self) -> bool:
        """Returns True if the window we think is currently active is actually active."""

        AXObject.clear_cache(self._window, False, "Ensuring the active window is really active.")
        is_active = _get_ax_utilities().is_active(self._window)
        _log_tokens([self._window, "is active:", is_active])
        return is_active

    def get_active_window(self) -> Optional[Atspi.Accessible]:
        """Returns the currently-active window (i.e. without searching or verifying)."""

        _log_tokens(["Active window is", self._window], stack=True)
        return self._window

    def set_active_window(
        self,
        frame: Optional[Atspi.Accessible],
        app: Optional[Atspi.Accessible] = None,
        set_window_as_focus: bool = False,
        notify_script: bool = False
    ) -> None:
        """Sets the active window."""

        tokens = ["Request to set active window to", frame]
        if app is not None:
            tokens.extend(["in", app])
        _log_tokens(tokens)

        if frame is None and AXObject.has_broken_popup_ancestry(self._focus):
            _log_tokens(
                ["Not clearing active window; focus", self._focus, "is in popup with broken ancestry"],
                "broken-popup-ancestry",
            )
            return

        if frame == self._window:
            _log("Setting active window to existing active window", "no-change")
        elif frame is None:
            self._window = None
            cthulhu_state.activeWindow = None
        else:
            self._window = frame
            cthulhu_state.activeWindow = frame

        contextObject = self._focus
        if set_window_as_focus:
            self.set_locus_of_focus(None, self._window, notify_script)
        elif not (self.focus_is_active_window() or self.focus_is_in_active_window()):
            _log_tokens(["Focus", self._focus, "is not in", self._window], stack=True)

            if self.active_window_is_cthulhu():
                _log_tokens(
                    ["Skipping focused-object lookup and script activation for self-hosted window", self._window],
                    "self-window",
                )
                return
            else:
                focusedObject = self.find_focused_object()
                if focusedObject is not None and focusedObject != self._window:
                    _log_tokens(["Using focused object", focusedObject, "from active window", self._window])
                    self.set_locus_of_focus(None, focusedObject, notify_script=True)
                    contextObject = focusedObject
                elif self._focus is None:
                    _log_tokens(["No previous focus. Falling back to active window", self._window])
                    self.set_locus_of_focus(None, self._window, notify_script=True)
                    contextObject = self._window
                # Don't update the focus to the active window if we can't get to the active window
                # from the focused object. https://bugreports.qt.io/browse/QTBUG-130116
                elif not AXObject.has_broken_ancestry(self._focus):
                    self.set_locus_of_focus(None, self._window, notify_script=True)
                    contextObject = self._window

        if contextObject is None:
            contextObject = self._window

        app = _get_ax_utilities().get_application(contextObject)
        self.app.scriptManager.activate_script_for_context(app, contextObject, "focus: active-window")

    @dbus_service.command
    def toggle_presentation_mode(
        self,
        script: default.Script,
        event: Optional[InputEvent] = None,
        notify_user: bool = True
    ) -> bool:
        """Switches between browse mode and focus mode (web content only)."""

        return script.toggle_presentation_mode(event, document=None, notify_user=notify_user)

    @dbus_service.command
    def toggle_layout_mode(
        self,
        script: default.Script,
        event: Optional[InputEvent] = None,
        notify_user: bool = True
    ) -> bool:
        """Switches between object mode and layout mode for line presentation (web content only)."""

        return script.toggle_layout_mode(event, notify_user=notify_user)

    @dbus_service.command
    def enable_sticky_browse_mode(
        self,
        script: default.Script,
        event: Optional[InputEvent] = None,
        notify_user: bool = True
    ) -> bool:
        """Enables sticky browse mode (web content only)."""

        return script.enable_sticky_browse_mode(event, force_message=notify_user)

    @dbus_service.command
    def enable_sticky_focus_mode(
        self,
        script: default.Script,
        event: Optional[InputEvent] = None,
        notify_user: bool = True
    ) -> bool:
        """Enables sticky focus mode (web content only)."""

        return script.enable_sticky_focus_mode(event, force_message=notify_user)

    @dbus_service.getter
    def get_in_layout_mode(self) -> bool:
        """Returns True if layout mode (as opposed to object mode) is active (web content only)."""

        if script := self.app.scriptManager.get_active_script():
            return script.in_layout_mode()
        return False

    @dbus_service.getter
    def get_in_focus_mode(self) -> bool:
        """Returns True if focus mode is active (web content only)."""

        if script := self.app.scriptManager.get_active_script():
            return script.in_focus_mode()
        return False

    @dbus_service.getter
    def get_focus_mode_is_sticky(self) -> bool:
        """Returns True if focus mode is active and 'sticky' (web content only)."""

        if script := self.app.scriptManager.get_active_script():
            return script.focus_mode_is_sticky()
        return False

    @dbus_service.getter
    def get_browse_mode_is_sticky(self) -> bool:
        """Returns True if browse mode is active and 'sticky' (web content only)."""

        if script := self.app.scriptManager.get_active_script():
            return script.browse_mode_is_sticky()
        return False

_manager: Optional[FocusManager] = None
def get_manager() -> Optional[FocusManager]:
    """Returns the Focus Manager"""

    global _manager
    if _manager is None:
        try:
            from . import cthulhu
            if cthulhu.cthulhuApp:
                _manager = FocusManager(cthulhu.cthulhuApp)
        except (ImportError, AttributeError):
            pass
    return _manager
