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

"""Hello Cthulhu plugin for Cthulhu."""

import logging
import weakref
from cthulhu.plugin import Plugin, cthulhu_hookimpl

logger = logging.getLogger(__name__)

# Class-level variable to track if the greeting has been presented
# This ensures the greeting is only shown once even if multiple instances exist
_greeting_shown = False

class HelloCthulhu(Plugin):
    """Plugin that speaks a welcome message when Cthulhu starts up."""
    
    def __init__(self, *args, **kwargs):
        """Initialize the plugin."""
        super().__init__(*args, **kwargs)
        logger.info("HelloCthulhu plugin initialized")
        self._signal_handler_id = None
        self._is_connected = False
        
    @cthulhu_hookimpl
    def activate(self, plugin=None):
        """Activate the plugin."""
        # Skip if this activation call isn't for us
        if plugin is not None and plugin is not self:
            return
            
        logger.info("Activating HelloCthulhu plugin")
        try:
            # Only connect the signal if we haven't already
            if not self._is_connected:
                signal_manager = self.app.getSignalManager()
                self._signal_handler_id = signal_manager.connectSignal(
                    "start-application-completed",
                    self.process,
                    "default"  # Add profile parameter
                )
                self._is_connected = True
                logger.debug("Connected to start-application-completed signal")
        except Exception as e:
            logger.error(f"Error activating HelloCthulhu plugin: {e}")
            
    @cthulhu_hookimpl
    def deactivate(self, plugin=None):
        """Deactivate the plugin."""
        # Skip if this deactivation call isn't for us
        if plugin is not None and plugin is not self:
            return
            
        logger.info("Deactivating HelloCthulhu plugin")
        try:
            # Only disconnect if we're connected
            if self._is_connected and self._signal_handler_id is not None:
                signal_manager = self.app.getSignalManager()
                signal_manager.disconnectSignalByFunction(
                    self.process
                )
                self._signal_handler_id = None
                self._is_connected = False
                logger.debug("Disconnected from start-application-completed signal")
        except Exception as e:
            logger.error(f"Error deactivating HelloCthulhu plugin: {e}")
            
    def process(self, app):
        """Process the start-application-completed signal."""
        global _greeting_shown
        
        # Only present the message if it hasn't been shown yet
        if _greeting_shown:
            logger.debug("Greeting already shown, skipping")
            return
            
        try:
            messages = app.getDynamicApiManager().getAPI('Messages')
            state = app.getDynamicApiManager().getAPI('CthulhuState')
            if state.activeScript:
                state.activeScript.presentMessage(messages.START_CTHULHU, resetStyles=False)
                _greeting_shown = True
                logger.info("Greeting message presented")
                
                # Disconnect the signal after presenting the message
                if self._is_connected and self._signal_handler_id is not None:
                    signal_manager = app.getSignalManager()
                    signal_manager.disconnectSignalByFunction(
                        self.process
                    )
                    self._signal_handler_id = None
                    self._is_connected = False
                    logger.debug("Disconnected signal after presenting greeting")
        except Exception as e:
            logger.error(f"Error in HelloCthulhu process: {e}")
