#!/usr/bin/env python3
#
# Copyright (c) 2024 Stormux
# Copyright (c) 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

"""Script for sleep mode where Cthulhu ignores events and commands.

This script is now a minimal implementation that relies on the global
sleep mode flag in cthulhu_state.sleepMode to block speech and braille
at the system level.
"""

__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2024 Stormux"
__license__   = "LGPL"

import cthulhu.scripts.default as default
import cthulhu.debug as debug
import cthulhu.cthulhu_modifier_manager as cthulhu_modifier_manager
import cthulhu.sleep_mode_manager as sleep_mode_manager

class Script(default.Script):
    """The sleep mode script.
    
    This script now relies on the global sleep mode flag for blocking
    speech and braille output at the system level. It only handles
    keybinding management and basic event blocking.
    """

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

    def activate(self):
        """Called when this script is activated."""
        
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE SCRIPT: Activating", True)
        super().activate()
        cthulhu_modifier_manager.getManager().unsetCthulhuModifiers("Entering sleep mode.")

        # Get the manager and add its bindings and handlers
        manager = sleep_mode_manager.getManager()
        managerBindings = manager.getBindings()
        if hasattr(managerBindings, 'keyBindings'):
            for binding in managerBindings.keyBindings:
                self.keyBindings.add(binding)
        self.inputEventHandlers.update(manager.getHandlers())
        
        # Remove most key grabs except sleep mode toggle
        self.removeKeyGrabs()
        
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE SCRIPT: Activated successfully", True)

    def deactivate(self):
        """Called when this script is deactivated."""
        
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE SCRIPT: Deactivating", True)
        cthulhu_modifier_manager.getManager().refreshCthulhuModifiers("Exiting sleep mode.")
        
        super().deactivate()

    def removeKeyGrabs(self):
        """Remove key grabs except for sleep mode toggle."""
        
        try:
            # First remove all grabs inherited from default activation,
            # including modifier grabs.
            super().removeKeyGrabs()

            self.grab_ids = []
            for keyBinding in self.keyBindings.keyBindings:
                if hasattr(keyBinding, 'handler') and hasattr(keyBinding.handler, 'function'):
                    if hasattr(keyBinding.handler.function, '__name__'):
                        if 'toggleSleepMode' in keyBinding.handler.function.__name__:
                            # Keep sleep mode toggle
                            try:
                                import cthulhu
                                grabIds = cthulhu.addKeyGrab(keyBinding)
                                if grabIds:
                                    for grabId in grabIds:
                                        self.grab_ids.append(grabId)
                                        debug.printMessage(debug.LEVEL_INFO, f"SLEEP MODE: Kept sleep toggle key grab: {grabId}", True)
                            except Exception as e:
                                debug.printMessage(debug.LEVEL_INFO, f"SLEEP MODE: Error keeping key grab: {e}", True)
                        else:
                            debug.printMessage(debug.LEVEL_INFO, f"SLEEP MODE: Skipping key grab for {keyBinding.handler.function.__name__}", True)
                            
        except Exception as e:
            debug.printMessage(debug.LEVEL_INFO, f"SLEEP MODE: Error in removeKeyGrabs: {e}", True)

    # Block common event handlers as an additional layer of protection
    def onCaretMoved(self, event):
        """Block caret movement events."""
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE: Blocking onCaretMoved", True)
        return True

    def onTextDeleted(self, event):
        """Block text deletion events."""
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE: Blocking onTextDeleted", True)
        return True

    def onTextInserted(self, event):
        """Block text insertion events."""
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE: Blocking onTextInserted", True)
        return True

    def onFocusChanged(self, event):
        """Block focus change events."""
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE: Blocking onFocusChanged", True)
        return True

    def onWindowActivated(self, event):
        """Block window activation events."""
        debug.printMessage(debug.LEVEL_INFO, "SLEEP MODE: Blocking onWindowActivated", True)
        return True


def get_script(app):
    """Returns the script for the given application."""
    return Script(app)
