from . import command, STOP_PROCESSING, reply_fn
try:
    from .tts import read_helper
except ImportError:
    read_helper = lambda *args, **kwargs: None
import re
import html
import logging

logger = logging.getLogger("match-action")

config = {}

@command('(.+)', pass_groups=True, stop=False, prefix=False)
def match_response_handler(bea, bot, update, groups):
    text = groups[0]
    for (regex, response, as_tts) in config["matches"]:
        if re.search(regex, text, flags=re.I):
            if as_tts == "True":
                read_helper(bea, bot, update, response)
            else:
                bea.reply(response, quote=False)

@command('respond (with tts )?to (.+) with (.+)', pass_groups=True)
def register_response(bea, bot, update, groups):
    """ Register a match-response pair with Bea.

    The first argument is a regex to match on.
    When Bea encounters text which matches the regex, she responds with the given response. Optionally, when available, TTS is used.
    """
    as_tts, match_regex, response = groups
    as_tts = str(as_tts is not None) # toml limitation

    config["matches"].append((match_regex, response, as_tts))
    bea.reply("Prima.")

@command('delete response to (.+)', pass_groups=True)
def unregister_response(bea, bot, update, groups):
    """ Delete a match-response pair by regex. """
    match_regex = groups[0]
    for match_cfg in config["matches"]:
        if match_regex == match_cfg[0]:
            break
    else:
        return bea.reply("No such regex found.")

    config["matches"].remove(match_cfg)
    bea.reply("Prima.", quote=False)

@command('list responses')
def list_responses(bea, bot, update):
    """ List match-response pairs. """
    output = '\n'.join(
            f"<code>{html.escape(regex)}</code> → {html.escape(response)}" + (
                ' (TTS)' if as_tts == 'True' else '')
            for regex, response, as_tts in config["matches"])

    if not config["matches"]:
        output = "Er zijn geen match-response-paren geregistreerd."

    bea.reply(output, quote=False, parse_mode='HTML')

def init(bea, _config):
    global config
    config = _config
    if "matches" not in config:
        config["matches"] = []
    return [register_response, unregister_response, list_responses, match_response_handler]
