from . import command, STOP_PROCESSING, USER_SET, users_map
import random

config = None

import logging

logger = logging.getLogger("admin")

@command('ik ben (.+)', pass_groups=True)
def set_title(bea, bot, update, groups):
    title = groups[0]

    try:
        bot.set_chat_administrator_custom_title(update.effective_chat.id, update.effective_user.id, title)
    except:
        return bea.reply(f"That didn't work. Maybe you're using symbols that aren't allowed?")

@command('promote (' + USER_SET + ')', auth=True, pass_groups=True)
def promote(bea, bot, update, groups):
    logger.info("Calling promote_chat_member")
    users = groups[0]

    def promote_single(uid):
        bot.promote_chat_member(update.effective_chat.id, uid, can_change_info=True, can_delete_messages=True, can_invite_users=True, can_restrict_members=True, can_pin_messages=True, can_promote_members=False)

    users_map(bea, users, promote_single)

@command('demote (' + USER_SET + ')', auth=True, pass_groups=True)
def demote(bea, bot, update, groups):
    users = groups[0]

    def demote_single(uid):
        bot.promote_chat_member(update.effective_chat.id, uid, can_change_info=False, can_delete_messages=False, can_invite_users=False, can_restrict_members=False, can_pin_messages=False, can_promote_members=False)

    users_map(bea, users, demote_single)

@command('verhul me in (.+)', auth=True, pass_groups=True)
def verhul(bea, bot, update, groups):
    user = update.effective_user.id
    name = groups[0]
    if name not in bea.known_channels:
        return bea.reply(f"Wat is een {name}?")
    chat = bea.known_channels[name]

    try:
        bot.promote_chat_member(chat, user, can_change_info=True, can_delete_messages=True, can_invite_users=True, can_restrict_members=True, can_pin_messages=True, can_promote_members=False, is_anonymous=True)
    except:
        return bea.reply(f"Daar ben ik machteloos.")

    word = random.choice(bea.config['spelling']['known_words'])
    config['hulmap'][word] = user

    bea.reply(f'Onthul jezelf met woord: {word}')

@command('onthul (.+)', pass_groups=True)
def onthul(bea, bot, update, groups):
    user = config['hulmap'].get(groups[0])
    if not user:
        return
    chat = update.effective_chat.id
    if (chat == update.effective_user.id):
        return bea.reply("Je moet dit niet in PM sturen, maar in de groep waarin je bent verhuld!")
    del config['hulmap'][groups[0]]
    bot.promote_chat_member(chat, user, can_change_info=True, can_delete_messages=True, can_invite_users=True, can_restrict_members=True, can_pin_messages=True, can_promote_members=False, is_anonymous=False)

def init(bea, _config):
    global config
    config = _config
    if 'hulmap' not in config:
        config['hulmap'] = {}
    return [verhul, onthul, set_title, promote, demote]
