from . import command, USER
import random

config = None
aanheffen = []
afsluiters = []
handtekeningen = []

@command(f'(?:formeel|brief|b) {USER}, (.+)', inline=True, pass_groups=True)
def formeel(bea, bot, update, groups):
    """
    Werkt het beste in inline mode. Voorbeeld:
    @tfckbot ?b flevosap, wat een prachtige dag is het vandaag, nietwaar?
    """
    user = update.effective_user
    name, text = groups

    uid = bea.known_users.get(name.lower())
    set_name = config['names'].get(uid)
    if set_name:
        name = set_name

    if user.id in config['names']:
        my_name = config['names'][user.id]
    else:
        my_name = f'{user.first_name}'
        if user.last_name:
            my_name += f' {user.last_name}'

    afsluiter = random.choice(afsluiters)
    aanhef = random.choice(aanheffen).format(name=name)
    if random.random() > 0.5:
        handtekening = random.choice(handtekeningen).format(name=name)
        msg = f'{aanhef}\n\n{text}\n\n{afsluiter}\n\n{my_name}\n---\n{handtekening}'
    else:
        msg = f'{aanhef}\n\n{text}\n\n{afsluiter}\n\n{my_name}'

    if update.inline_query is not None:
        bea.inline_reply_text(msg)
    else:
        bea.reply(msg)


@command('briefnaam (.+)', pass_groups=True)
def set_briefnaam(bea, bot, update, groups):
    config['names'][update.effective_user.id] = groups[0]


def init(bea, _config):
    global config, aanheffen, afsluiters, handtekeningen
    config = _config
    if 'names' not in config:
        config['names'] = {}
    with open('letterstyle/aanhef.txt', 'r') as f:
        aanheffen = [*map(str.strip, f.readlines())]
    with open('letterstyle/afsluitingen.txt', 'r') as f:
        afsluiters = [*map(str.strip, f.readlines())]
    with open('letterstyle/handtekeningen.txt', 'r') as f:
        handtekeningen = [*map(str.strip, f.readlines())]
    return [set_briefnaam, formeel]
