import re


def respond_to(regex, flags=re.IGNORECASE):
    """Listen to messages mentioning the bot and matching a regex pattern

    This decorator will enable a Plugin method to listen to messages that are directed to the bot
    (ie. message starts by mentioning the bot) and match a regex pattern.
    The Plugin method will be called for each message that mentions the bot and matches the
    specified regex pattern. The received :py:class:`~machine.plugins.base.Message` will be passed
    to the method when called. Named groups can be used in the regex pattern, to catch specific
    parts of the message. These groups will be passed to the method as keyword arguments when
    called.

    :param regex: regex pattern to listen for
    :param flags: regex flags to apply when matching
    :return: wrapped method
    """

    def respond_to_decorator(f):
        f.metadata = getattr(f, "metadata", {})
        f.metadata['plugin_actions'] = f.metadata.get('plugin_actions', {})
        f.metadata['plugin_actions']['respond_to'] = \
            f.metadata['plugin_actions'].get('respond_to', {})
        f.metadata['plugin_actions']['respond_to']['regex'] = \
            f.metadata['plugin_actions']['respond_to'].get('regex', [])
        f.metadata['plugin_actions']['respond_to']['regex'].append(re.compile(regex, flags))
        return f

    return respond_to_decorator