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

"""GameMode plugin for Cthulhu - reduce speech interruption while gaming."""

from cthulhu.plugin import Plugin, cthulhu_hookimpl
from cthulhu import debug
from cthulhu import messages
from cthulhu import settings_manager

settingsManager = settings_manager.getManager()


class GameMode(Plugin):
    """Plugin that reduces speech interruption while holding keys."""

    def __init__(self, *args, **kwargs):
        """Initialize the GameMode plugin."""
        super().__init__(*args, **kwargs)
        self._activated = False
        self._kbBinding = None

        debug.printMessage(debug.LEVEL_INFO, "GameMode: Plugin initialized", True)

    @cthulhu_hookimpl
    def activate(self, plugin=None):
        """Activate the GameMode plugin."""
        if plugin is not None and plugin is not self:
            return

        if self._activated:
            debug.printMessage(debug.LEVEL_INFO, "GameMode: Already activated, skipping", True)
            return

        try:
            debug.printMessage(debug.LEVEL_INFO, "GameMode: Plugin activation starting", True)
            self._register_keybinding()
            self._activated = True
            debug.printMessage(debug.LEVEL_INFO, "GameMode: Plugin activated successfully", True)
            return True
        except Exception as error:
            debug.printMessage(debug.LEVEL_INFO, f"GameMode: ERROR activating plugin: {error}", True)
            return False

    @cthulhu_hookimpl
    def deactivate(self, plugin=None):
        """Deactivate the GameMode plugin."""
        if plugin is not None and plugin is not self:
            return

        try:
            debug.printMessage(debug.LEVEL_INFO, "GameMode: Plugin deactivation starting", True)
            settingsManager.setSetting('gameMode', False)
            self._activated = False
            debug.printMessage(debug.LEVEL_INFO, "GameMode: Plugin deactivated successfully", True)
            return True
        except Exception as error:
            debug.printMessage(debug.LEVEL_INFO, f"GameMode: ERROR deactivating plugin: {error}", True)
            return False

    def _register_keybinding(self):
        """Register the Cthulhu+Control+G keybinding for toggling game mode."""
        try:
            if not self.app:
                debug.printMessage(debug.LEVEL_INFO, "GameMode: No app reference for keybinding", True)
                return

            gestureString = "kb:cthulhu+control+g"
            description = "Toggle game mode"
            self._kbBinding = self.registerGestureByString(
                self._toggle_game_mode,
                description,
                gestureString,
                globalBinding=True
            )
            if self._kbBinding:
                debug.printMessage(debug.LEVEL_INFO, f"GameMode: Registered keybinding {gestureString}", True)
            else:
                debug.printMessage(debug.LEVEL_INFO, f"GameMode: Failed to register keybinding {gestureString}", True)
        except Exception as error:
            debug.printMessage(debug.LEVEL_INFO, f"GameMode: Error registering keybinding: {error}", True)

    def _toggle_game_mode(self, script, inputEvent=None):
        """Toggle game mode on or off."""
        currentValue = bool(settingsManager.getSetting('gameMode'))
        newValue = not currentValue
        settingsManager.setSetting('gameMode', newValue)

        message = messages.GAME_MODE_ENABLED if newValue else messages.GAME_MODE_DISABLED
        if script:
            script.presentMessage(message)
        return True
