import re


def listen_to(regex, flags=re.IGNORECASE):
    """Listen to messages matching a regex pattern

    This decorator will enable a Plugin method to listen to messages that match a regex pattern.
    The Plugin method will be called for each message that 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 listen_to_decorator(f):
        f.metadata = getattr(f, "metadata", {})
        f.metadata['plugin_actions'] = f.metadata.get('plugin_actions', {})
        f.metadata['plugin_actions']['listen_to'] = \
            f.metadata['plugin_actions'].get('listen_to', {})
        f.metadata['plugin_actions']['listen_to']['regex'] = \
            f.metadata['plugin_actions']['listen_to'].get('regex', [])
        f.metadata['plugin_actions']['listen_to']['regex'].append(re.compile(regex, flags))
        return f

    return listen_to_decorator