#!/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.

"""Base class for Cthulhu plugins using pluggy."""

import os
import logging

# Import pluggy for hook specifications
try:
    import pluggy
    cthulhu_hookimpl = pluggy.HookimplMarker("cthulhu")
    PLUGGY_AVAILABLE = True
    logging.getLogger(__name__).info("Successfully imported pluggy")
except ImportError:
    # Fallback if pluggy is not available
    def cthulhu_hookimpl(func=None, **kwargs):
        """Fallback decorator when pluggy is not available.
        
        This is a no-op decorator that returns the original function.
        It allows the code to continue working without pluggy, though
        plugins will be disabled.
        """
        if func is None:
            return lambda f: f
        return func
    PLUGGY_AVAILABLE = False
    logging.getLogger(__name__).warning("Pluggy not available, plugins will be disabled")
    import traceback
    logging.getLogger(__name__).debug(traceback.format_exc())

logger = logging.getLogger(__name__)

class Plugin:
    """Base class for Cthulhu plugins."""

    def __init__(self):
        """Initialize the plugin with default attributes."""
        self.app = None
        self.plugin_info = None
        self.module_name = ''
        self.name = ''
        self.version = ''
        self.description = ''

    def set_app(self, app):
        """Set the application reference."""
        self.app = app

    def set_plugin_info(self, plugin_info):
        """Set plugin information and extract relevant attributes."""
        self.plugin_info = plugin_info
        if plugin_info:
            self.module_name = getattr(plugin_info, 'module_name', '')
            self.name = getattr(plugin_info, 'name', '')
            self.version = getattr(plugin_info, 'version', '')
            self.description = getattr(plugin_info, 'description', '')

    @cthulhu_hookimpl
    def activate(self, plugin=None):
        """Activate the plugin. Override this in subclasses."""
        if plugin is not None and plugin is not self:
            return
        logger.info(f"Activating plugin: {self.name}")

    @cthulhu_hookimpl
    def deactivate(self, plugin=None):
        """Deactivate the plugin. Override this in subclasses."""
        if plugin is not None and plugin is not self:
            return
        logger.info(f"Deactivating plugin: {self.name}")

    def registerGestureByString(self, function, name, gestureString, learnModeEnabled=True):
        """Register a gesture by string."""
        if self.app:
            api_helper = self.app.getAPIHelper()
            if api_helper:
                return api_helper.registerGestureByString(
                    function, 
                    name, 
                    gestureString, 
                    'default', 
                    'cthulhu', 
                    learnModeEnabled, 
                    contextName=self.module_name
                )
        return None
