from telegram import Update
from telegram.ext import Updater, CallbackContext, ConversationHandler, CommandHandler, MessageHandler, Filters

from db import DBConnector

import re

str_matcher = r"\"(?P<name>.+)\"\s*(?P<fat>\d+)\s*/\s*(?P<protein>\d+)\s*/\s*(?P<carbohydrates>\d+)\s*(?P<kcal>\d+)"

ADD_1 = 0


def add_0(update: Update, _: CallbackContext):
    update.message.reply_text('Enter new product in format\n'
                              '"name" fat/protein/carbohydrates kcal')
    return ADD_1


def add_1(update: Update, context: CallbackContext):
    db_connect: DBConnector = context.bot_data['db_connect']
    result = re.match(str_matcher, update.message.text)
    if result:
        db_connect.products.insert(result.groupdict())
        update.message.reply_text('Product was added')
    else:
        update.message.reply_text('Message have wrong format')
    return ConversationHandler.END


def add_handler(updater: Updater):
    """/product_add - Add product to list known products"""
    updater.dispatcher.add_handler(ConversationHandler(
        entry_points=[CommandHandler('product_add', add_0)],
        states={
            ADD_1: [MessageHandler(Filters.text & ~Filters.command, add_1)]
        },
        fallbacks=[]
    ))

[((21, 13, 21, 55), 're.match', 're.match', ({(21, 22, 21, 33): 'str_matcher', (21, 35, 21, 54): 'update.message.text'}, {}), '(str_matcher, update.message.text)', False, 'import re\n'), ((33, 22, 33, 58), 'telegram.ext.CommandHandler', 'CommandHandler', ({(33, 37, 33, 50): '"""product_add"""', (33, 52, 33, 57): 'add_0'}, {}), "('product_add', add_0)", False, 'from telegram.ext import Updater, CallbackContext, ConversationHandler, CommandHandler, MessageHandler, Filters\n'), ((35, 20, 35, 74), 'telegram.ext.MessageHandler', 'MessageHandler', ({(35, 35, 35, 66): '(Filters.text & ~Filters.command)', (35, 68, 35, 73): 'add_1'}, {}), '(Filters.text & ~Filters.command, add_1)', False, 'from telegram.ext import Updater, CallbackContext, ConversationHandler, CommandHandler, MessageHandler, Filters\n')]