from . import command
from .inline_keyboard_utils import generate_keyboard
from telegram import InlineKeyboardMarkup

config = None

def update_plusone(bea, bot, update):
    query = update.callback_query
    metadata = config['metadata'][query.message.message_id]
    if query.from_user.id in metadata['already_voted']:
        query.answer()
        return
    else:
        metadata['already_voted'].append(query.from_user.id)
    is_f = query.data.startswith('f')
    data = int(query.data.split(';')[1])
    data += 1
    keeb = generate_keyboard([f'+1 ({data})' if not is_f else f'F ({data})'], [f'po;{data}' if not is_f else f'f;{data}'])
    query.edit_message_reply_markup(InlineKeyboardMarkup(keeb))

@command('F$', pass_groups=True)
def F(bea, bot, update, groups):
    keeb = generate_keyboard(['F (0)'], ['f;0'])
    msg = bea.reply("Press F to pay respects", reply_markup=InlineKeyboardMarkup(keeb), quote=False)

    config['metadata'][msg.message_id] = {'already_voted': []}

@command('plusone(.+)?', pass_groups=True)
def plusone(bea, bot, update, groups):
    text = groups[0]
    if not text and update.effective_message.reply_to_message and update.effective_message.reply_to_message.text:
        text = update.effective_message.reply_to_message.text
    elif not text:
        return
    keeb = generate_keyboard(['+1 (0)'], ['po;0'])
    msg = bea.reply(text, reply_markup=InlineKeyboardMarkup(keeb), quote=False)

    config['metadata'][msg.message_id] = {'already_voted': []}


def init(bea, _config):
    global config
    config = _config
    if 'metadata' not in config:
        config['metadata'] = {}
    bea.callback_handler['po'] = update_plusone
    bea.callback_handler['f'] = update_plusone
    return [F, plusone]
