"""
Define the PluginConfig and Plugin classes, plus the SafetyMetaclass.
These are used in the plugin system added in poezio 0.7.5
(see plugin_manager.py)
"""

from typing import Any, Dict, Set, Optional, TYPE_CHECKING, Callable, Type
from configparser import RawConfigParser
from pathlib import Path
from poezio.timed_events import TimedEvent, DelayedEvent
from poezio.ui.types import Message
from poezio import tabs
from poezio.core.tabs import Tabs
from poezio.core.structs import Status, GenericCompletion
from poezio import config
import inspect
import traceback
import logging
log = logging.getLogger(__name__)


if TYPE_CHECKING:
    from poezio.core.core import Core
    from poezio.ui.types import BaseMessage
    from poezio.plugin_manager import PluginManager


class PluginConfig(config.Config):
    """
    Plugin configuration object.
    They are accessible inside the plugin with self.config
    and behave like the core Config object.
    """

    def __init__(self, filename: Path, module_name: str,
                 default: dict[Any, Any] | None = None) -> None:
        config.Config.__init__(self, filename, default=default)
        self.module_name = module_name
        self.default_section = module_name
        self.read()

    def get(self, option: str, default: config.ConfigValue | None = None,
            section: str | None = None):
        if not section:
            section = self.module_name
        return config.Config.get(self, option, default, section)

    def set(self, option: str, value: config.ConfigValue,
            section: str | None = None) -> None:
        if not section:
            section = self.module_name
        config.Config.set_and_save(self, option, value, section)

    def remove(self, option: str, section: str | None = None) -> tuple[str, str]:
        if not section:
            section = self.module_name
        return config.Config.remove_and_save(self, option, section)

    def read(self) -> None:
        """Read the config file"""
        RawConfigParser.read(self.configparser, str(self.file_name))
        if not self.has_section(self.module_name):
            self.add_section(self.module_name)

    def options(self, section: str | None = None) -> list[str]:
        """
            Return the options of the section
            If no section is given, it defaults to the plugin name.
        """
        if not section:
            section = self.module_name
        if not self.has_section(section):
            self.add_section(section)
        return config.Config.options(self, section)

    def write(self) -> bool:
        """Write the config to the disk"""
        try:
            with self.file_name.open('w') as fp:
                RawConfigParser.write(self.configparser, fp)
        except IOError:
            return False
        return True


class SafetyMetaclass(type):
    # A hack
    core: 'Core | None' = None

    @staticmethod
    def safe_func(f):
        def helper(*args, **kwargs):
            passthrough = kwargs.pop('passthrough', False)
            try:
                return f(*args, **kwargs)
            except Exception:
                if passthrough:
                    raise
                if inspect.stack()[1][1] == inspect.getfile(f):
                    raise
                elif SafetyMetaclass.core:
                    log.exception('Error in a plugin')
                    SafetyMetaclass.core.information(traceback.format_exc(),
                                                     'Error')
                    return None

        async def async_helper(*args, **kwargs):
            passthrough = kwargs.pop('passthrough', False)
            try:
                return await f(*args, **kwargs)
            except Exception:
                if passthrough:
                    raise
                if inspect.stack()[1][1] == inspect.getfile(f):
                    raise
                elif SafetyMetaclass.core:
                    log.exception('Error in a plugin')
                    SafetyMetaclass.core.information(traceback.format_exc(),
                                                     'Error')
                    return None
        if inspect.iscoroutinefunction(f):
            return async_helper
        return helper

    def __new__(meta, name, bases, class_dict):
        for k, v in class_dict.items():
            if inspect.isfunction(v):
                if k != '__init__' and k != 'init':
                    class_dict[k] = SafetyMetaclass.safe_func(v)
        return type.__new__(meta, name, bases, class_dict)


class PluginAPI:
    """
    The public API exposed to the plugins.
    Its goal is to limit the use of the raw Core object
    as much as possible.
    """

    def __init__(self, core: 'Core', plugin_manager: 'PluginManager', module_name: str) -> None:
        self.core = core
        self.plugin_manager = plugin_manager
        self.module_name = module_name

    def send_message(self, msg: str) -> bool:
        """
        Send a message to the current tab.

        :param str msg: The message to send.
        """
        return self.core.send_message(msg)

    def find_message(self, time: str, format: str) -> Optional[Message]:
        """Find a message from a timestamp.

        :param time: A timestamp used to find the message.
        :param format: The format of the timestamp.
        :returns: A Message or None
        """
        for message in reversed(self.core.get_conversation_messages()):
            if isinstance(message, Message) and \
               message.time.strftime(format) == time:
                return message
        return None

    def get_conversation_messages(self) -> 'list[BaseMessage]':
        """
        Get all the Messages of the current Tab.

        :returns: The list of :py:class:`text_buffer.Message` objects.
        :returns: None if the Tab does not inherit from ChatTab.
        :rtype: :py:class:`list`
        """
        return self.core.get_conversation_messages()

    def add_timed_event(self, event: DelayedEvent) -> None:
        """
        Schedule a timed event.

        :param timed_events.TimedEvent event: The timed event to schedule.
        """
        return self.core.add_timed_event(event)

    def remove_timed_event(self, event: DelayedEvent) -> None:
        """
        Unschedule a timed event.

        :param timed_events.TimedEvent event: The event to unschedule.
        """
        return self.core.remove_timed_event(event)

    def create_timed_event(self, *args, **kwargs) -> TimedEvent:
        """
        Create a timed event, but do not schedule it;
        :py:func:`~PluginAPI.add_timed_event` must be used for that.

        :param datetime.datetime date: The time at which the handler must be executed
        :param function callback: The handler that will be executed
        :param args: Optional arguments passed to the handler.
        :return: The created event.
        :rtype: :py:class:`timed_events.TimedEvent`
        """
        return TimedEvent(*args, **kwargs)

    def create_delayed_event(self, *args, **kwargs) -> DelayedEvent:
        """
        Create a delayed event, but do not schedule it;
        :py:func:`~PluginAPI.add_timed_event` must be used for that.

        A delayed event is a timed event with a delay from the time
        this function is called (instead of a datetime).

        :param int delay: The number of seconds to schedule the execution
        :param function callback: The handler that will be executed
        :param args: Optional arguments passed to the handler.
        :return: The created event.
        :rtype: :py:class:`timed_events.DelayedEvent`
        """
        return DelayedEvent(*args, **kwargs)

    def information(self, msg: str, typ: str = '') -> bool:
        """
        Display a new message in the information buffer.

        :param str msg: The message to display.
        :param str typ: The message type (e.g. Info, Error…)
        """
        return self.core.information(msg=msg, typ=typ)

    def current_tab(self) -> tabs.Tab:
        """
        Get the current Tab.

        :returns: The current tab.
        """
        return self.core.tabs.current_tab

    def get_status(self) -> Status:
        """
        Get the current user global status.

        :returns Status: The current status.
        """
        return self.core.get_status()

    def run_command(self, text: str) -> bool:
        """
        Run a command from the current tab.
        (a command starts with a /, if not, it’s a message)

        :param str line: The command to run.
        """
        return self.core.tabs.current_tab.execute_command(text)

    def all_tabs(self) -> Tabs:
        """
        Return a list of all opened tabs

        :returns list: The list of tabs.
        """
        return self.core.tabs

    def add_command(self,
                    name: str,
                    handler: Callable[[str], Any], help: str, *,
                    completion: GenericCompletion = None,
                    short: str = '', usage: str = '') -> None:
        """
        Add a global command.

        :param str name: The name of the command (/name)
        :param function handler: The function called when the command is run.
        :param str help: The complete help for that command.
        :param str short: A short description of the command.
        :param function completion: The completion function for that command
            (optional)
        :param str usage: A string showing the required and optional args
            of the command. Optional args should be surrounded by []
            and mandatory args should be surrounded by <>.

            Example string: "<server> [port]"

        :raises Exception: If the command already exists.
        """
        return self.plugin_manager.add_command(self.module_name, name, handler,
                                               help=help, completion=completion,
                                               short=short, usage=usage)

    def del_command(self, name: str) -> None:
        """
        Remove a global command.

        :param str name: The name of the command to remove.
            That command _must_ have been added by the same plugin
        """
        return self.plugin_manager.del_command(self.module_name, name)

    def add_key(self, key: str, handler: Callable[..., Any]) -> None:
        """
        Associate a global binding to a handler.

        :param str key: The curses representation of the binding.
        :param function handler: The function called when the binding is pressed.

        :raise Exception: If the binding is already present.
        """
        return self.plugin_manager.add_key(self.module_name, key, handler)

    def del_key(self, key: str) -> None:
        """
        Remove a global binding.

        :param str key: The binding to remove.
        """
        return self.plugin_manager.del_key(self.module_name, key)

    def add_tab_key(self, tab_type: Type[tabs.Tab], key: str,
                    handler: Callable[..., Any]) -> None:
        """
        Associate a binding to a handler, but only for a certain tab type.

        :param Tab tab_type: The type of tab to target.
        :param str key: The binding to add.
        :param function handler: The function called when the binding is pressed
        """
        return self.plugin_manager.add_tab_key(self.module_name, tab_type,
                                               key, handler)

    def del_tab_key(self, tab_type: Type[tabs.Tab], key: str) -> None:
        """
        Remove a binding added with add_tab_key

        :param tabs.Tab tab_type: The type of tab to target.
        :param str key: The binding to remove.
        """
        return self.plugin_manager.del_tab_key(self.module_name, tab_type, key)

    def add_tab_command(self,
                        tab_type: Type[tabs.Tab],
                        name: str,
                        handler: Callable[[str], Any], help: str, *,
                        completion: GenericCompletion = None,
                        short: str = '', usage: str = '') -> None:
        """
        Add a command to only one type of tab.

        :param tabs.Tab tab_type: The type of Tab to target.
        :param str name: The name of the command (/name)
        :param function handler: The function called when the command is run.
        :param str help: The complete help for that command.
        :param str short: A short description of the command.
        :param function completion: The completion function for that command
            (optional)
        :param str usage: A string showing the required and optional args
            of the command. Optional args should be surrounded by []
            and mandatory args should be surrounded by <>.

            Example string: "<server> [port]"

        :raise Exception: If the command already exists.
        """
        return self.plugin_manager.add_tab_command(
            self.module_name, tab_type, name, handler,
            help=help, completion=completion,
            short=short, usage=usage,
        )

    def del_tab_command(self, tab_type: Type[tabs.Tab], name: str) -> None:
        """
        Remove a tab-specific command.

        :param tabs.Tab tab_type: The type of tab to target.
        :param str name: The name of the command to remove.
            That command _must_ have been added by the same plugin
        """
        return self.plugin_manager.del_tab_command(self.module_name, tab_type, name)

    def add_event_handler(self, event_name: str, handler: Callable[..., Any],
                          priority: int = 50) -> None:
        """
        Add an event handler for a poezio event.

        :param str event_name: The event name.
        :param function handler: The handler function.
        :param int position: The position of that handler in the handler list.
            This is useful for plugins like OTR, which must be the last
            function called on the text.
            Defaults to 0.

        A complete list of those events can be found at
        https://doc.poez.io/dev/events.html
        """
        return self.plugin_manager.add_event_handler(
            self.module_name, event_name, handler, priority,
        )

    def del_event_handler(self, event_name: str, handler: Callable) -> None:
        """
        Remove a handler for a poezio event.

        :param str event_name: The name of the targeted event.
        :param function handler: The function to remove from the handlers.
        """
        return self.plugin_manager.del_event_handler(
            self.module_name, event_name, handler,
        )

    def add_slix_event_handler(self, event_name: str, handler: Callable[..., Any]) -> None:
        """
        Add an event handler for a slixmpp event.

        :param str event_name: The event name.
        :param function handler: The handler function.

        A list of the slixmpp events can be found here
        http://sleekxmpp.com/event_index.html
        """
        self.core.xmpp.add_event_handler(event_name, handler)

    def del_slix_event_handler(self, event_name: str, handler: Callable[..., Any]) -> None:
        """
        Remove a handler for a slixmpp event

        :param str event_name: The name of the targeted event.
        :param function handler: The function to remove from the handlers.
        """
        self.core.xmpp.del_event_handler(event_name, handler)


class BasePlugin(object, metaclass=SafetyMetaclass):
    """
    Class that all plugins derive from.
    """

    # Internal use only
    _unloading = False

    default_config: Optional[Dict[Any, Any]] = None
    dependencies: Set[str] = set()
    # This dict will get populated when the plugin is initialized
    refs: Dict[str, Any] = {}

    def __init__(self, name: str, plugin_api: 'PluginAPI', core: 'Core', plugins_conf_dir: Path) -> None:
        self.__name = name
        self.core = core
        # More hack; luckily we'll never have more than one core object
        SafetyMetaclass.core = core
        conf = plugins_conf_dir / (self.__name + '.cfg')
        try:
            self.config = PluginConfig(
                conf, self.__name, default=self.default_config)
        except Exception:
            log.debug('Error while creating the plugin config', exc_info=True)
            self.config = PluginConfig(conf, self.__name)
        self._api = plugin_api
        self.init()

    @property
    def name(self) -> str:
        """
        Get the name (module name) of the plugin.
        """
        return self.__name

    @property
    def api(self) -> 'PluginAPI':
        return self._api

    def init(self) -> None:
        """
        Method called at the creation of the plugin.

        Do not overwrite __init__ and use this instead.
        """
        pass

    def cleanup(self) -> None:
        """
        Called when the plugin is unloaded.

        Overwrite this if you want to erase or save things before the plugin is disabled.
        """
        pass

    def unload(self) -> None:
        self.cleanup()

    def add_command(self,
                    name: str,
                    handler: Callable[[str], Any], help: str, *,
                    completion: GenericCompletion = None,
                    short: str = '', usage: str = '') -> None:
        """
        Add a global command.

        :param str name: The name of the command (/name)
        :param function handler: The function called when the command is run.
        :param str help: The complete help for that command.
        :param str short: A short description of the command.
        :param function completion: The completion function for that command
            (optional)
        :param str usage: A string showing the required and optional args
            of the command. Optional args should be surrounded by []
            and mandatory args should be surrounded by <>.

            Example string: "<server> [port]"

        :raises Exception: If the command already exists.
        """
        return self.api.add_command(name, handler,
                                    help=help, completion=completion,
                                    short=short, usage=usage)

    def del_command(self, name: str) -> None:
        """
        Remove a global command.

        :param str name: The name of the command to remove.
            That command _must_ have been added by the same plugin
        """
        return self.api.del_command(name)

    def add_key(self, key: str, handler: Callable[..., Any]) -> None:
        """
        Associate a global binding to a handler.

        :param str key: The curses representation of the binding.
        :param function handler: The function called when the binding is pressed.

        :raise Exception: If the binding is already present.
        """
        return self.api.add_key(key, handler)

    def del_key(self, key: str) -> None:
        """
        Remove a global binding.

        :param str key: The binding to remove.
        """
        return self.api.del_key(key)

    def add_tab_key(self, tab_type: Type[tabs.Tab], key: str, handler: Callable[..., Any]) -> None:
        """
        Associate a binding to a handler, but only for a certain tab type.

        :param Tab tab_type: The type of tab to target.
        :param str key: The binding to add.
        :param function handler: The function called when the binding is pressed
        """
        return self.api.add_tab_key(tab_type, key, handler)

    def del_tab_key(self, tab_type: Type[tabs.Tab], key: str) -> None:
        """
        Remove a binding added with add_tab_key

        :param tabs.Tab tab_type: The type of tab to target.
        :param str key: The binding to remove.
        """
        return self.api.del_tab_key(tab_type, key)

    def add_tab_command(self,
                        tab_type: Type[tabs.Tab],
                        name: str,
                        handler: Callable[[str], Any], help: str, *,
                        completion: GenericCompletion = None,
                        short: str = '', usage: str = '') -> None:
        """
        Add a command to only one type of tab.

        :param tabs.Tab tab_type: The type of Tab to target.
        :param str name: The name of the command (/name)
        :param function handler: The function called when the command is run.
        :param str help: The complete help for that command.
        :param str short: A short description of the command.
        :param function completion: The completion function for that command
            (optional)
        :param str usage: A string showing the required and optional args
            of the command. Optional args should be surrounded by []
            and mandatory args should be surrounded by <>.

            Example string: "<server> [port]"

        :raise Exception: If the command already exists.
        """
        return self.api.add_tab_command(
            tab_type, name, handler,
            help=help, completion=completion,
            short=short, usage=usage,
        )

    def del_tab_command(self, tab_type: Type[tabs.Tab], name: str) -> None:
        """
        Remove a tab-specific command.

        :param tabs.Tab tab_type: The type of tab to target.
        :param str name: The name of the command to remove.
            That command _must_ have been added by the same plugin
        """
        return self.api.del_tab_command(tab_type, name)

    def add_event_handler(self, event_name: str, handler: Callable[..., Any],
                          priority: int = 50) -> None:
        """
        Add an event handler for a poezio event.

        :param str event_name: The event name.
        :param function handler: The handler function.
        :param int position: The position of that handler in the handler list.
            This is useful for plugins like OTR, which must be the last
            function called on the text.
            Defaults to 0.

        A complete list of those events can be found at
        https://doc.poez.io/dev/events.html
        """
        return self.api.add_event_handler(
            event_name, handler, priority,
        )

    def del_event_handler(self, event_name: str, handler: Callable[..., Any]) -> None:
        """
        Remove a handler for a poezio event.

        :param str event_name: The name of the targeted event.
        :param function handler: The function to remove from the handlers.
        """
        return self.api.del_event_handler(
            event_name, handler,
        )
