from var import bannedids, jokes, bot
from uuid import uuid4
from telegram import InlineQueryResultArticle, InputTextMessageContent, Update, InlineKeyboardButton, \
    InlineKeyboardMarkup
from random import choice
from io import BytesIO
from memer import make as makememe
from PIL import Image, ImageDraw
import data


def msghandler(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.text is not None:
        if update.message.text.lower().startswith('/add '):
            if update.message.reply_to_message is None:
                update.message.reply_text('Must reply to the list message.')
                return
            if update.message.reply_to_message.from_user.username != 'SpaceTheBot':
                update.message.reply_text('Must reply to the list message.')
                return
            if update.message.reply_to_message.text.startswith('List'):
                pass
            else:
                update.message.reply_text('Must reply to the list message.')
                return
            try:
                num = int(update.message.reply_to_message.text.splitlines()
                          [len(update.message.reply_to_message.text.splitlines()) - 1].split('.')[0]) + 1
            except:
                num = 1
            text = update.message.text[5:]
            letter = text[0].upper()
            text = letter + text[1:]
            update.message.reply_to_message.edit_text(update.message.reply_to_message.text +
                                                      f'\n{num}. {text}')
            try:
                update.message.delete()
            except:
                pass
        if update.message.text.lower().startswith('/edit '):
            if update.message.reply_to_message is None:
                update.message.reply_text('Must reply to the list message.')
                return
            if update.message.reply_to_message.from_user.username != 'SpaceTheBot':
                update.message.reply_text('Must reply to the list message.')
                return
            if update.message.reply_to_message.text.startswith('List'):
                pass
            else:
                update.message.reply_text('Must reply to the list message.')
                return
            try:
                num = int(update.message.text.split(' ')[1])
            except:
                update.message.reply_text('Item number must be a number, not ' + update.message.text.split(' ')[1] +
                                          ' (contains non-number characters)')
                return
            if num > len(update.message.reply_to_message.text.splitlines()) - 2:
                update.message.reply_text('Item number must be on list.')
                return
            text = update.message.reply_to_message.text.splitlines()
            newtext = update.message.text.split(' ')[2:]
            newtext_ = ''
            for i in newtext:
                newtext_ += ' ' + i
            letter = newtext_[0].upper()
            newtext_ = letter + newtext_[1:]
            text[num - 1 + 2] = f'{num}.{newtext_}'
            text_ = ''
            for i in text:
                text_ += '\n' + i
            update.message.reply_to_message.edit_text(text_)
            try:
                update.message.delete()
            except:
                pass
    if len(update.message.photo) > 0 and update.message.from_user.id in data.pending_512pic:
        fileid = update.message.photo[len(update.message.photo) - 1].file_id
        m = update.message.reply_text('Processing image...')
        file = bot.getFile(fileid)
        img = BytesIO()
        img.write(file.download_as_bytearray())
        img.seek(0)
        newimg = BytesIO()
        img = Image.open(img)
        w, h = img.size
        if w == h:
            w, h = 512, 512
        if w > h:
            h = round((h / w) * 512)
            w = 512
        if h > w:
            w = round((w / h) * 512)
            h = 512
        img = img.resize((w, h))
        img.save(newimg, 'PNG')
        newimg.seek(0)
        update.message.reply_sticker(newimg)
        m.edit_text(
            'Your image is done, forward it to @stickers bot after using '
            '/addsticker command to add it to your pack.'
        )
        data.pending_512pic.remove(update.message.from_user.id)
        return
    if len(update.message.photo) > 0 and update.message.from_user.id in data.pending_addtext:
        fileid = update.message.photo[len(update.message.photo) - 1].file_id
        m = update.message.reply_text('Processing image...')
        file = bot.getFile(fileid)
        io = BytesIO()
        io.write(file.download_as_bytearray())
        io.seek(0)
        params = data.pending_addtextdata[str(update.message.from_user.id)]
        newim = makememe(io, params[0], params[1])
        update.message.reply_photo(newim)
        m.edit_text('Text processing is done.')
        data.pending_addtextdata.pop(str(update.message.from_user.id))
        data.pending_addtext.remove(update.message.from_user.id)
        return


def callback(update: Update, context):
    if update.callback_query.from_user.id in bannedids:
        update.callback_query.answer('You are banned from Space.')
        return
    if update.callback_query.data in ('mathquiz_wrong', 'mathquiz_getanswer', 'mathquiz_stopquestion') or \
            update.callback_query.data.startswith('mathquiz_correct'):
        mathdata = data.ongoingmathq[update.callback_query.message.chat.id]
        if update.callback_query.data == 'mathquiz_stopquestion':
            name = update.callback_query.from_user.first_name
            if update.callback_query.from_user.last_name is not None:
                name += ' ' + update.callback_query.from_user.last_name
            if update.callback_query.from_user.username is not None:
                name += f' (@{update.callback_query.from_user.username})'
            bot.editMessageText(f'Question:\n{mathdata.latestn1} + {mathdata.latestn2} + '
                                f'{mathdata.latestn3} = {mathdata.latestanswer}'
                                f'\n\nQuestion is ended by {name}.', mathdata.latestchatid, mathdata.latestmsgid)
            data.ongoingmathq.pop(update.callback_query.message.chat.id)
            return
        if update.callback_query.data == 'mathquiz_getanswer':
            update.callback_query.answer(
                f'You seriously gave up?\nWhat a noob.\nThe answer is {mathdata.latestanswer}.',
                show_alert=True)
            mathdata.gotanswer.append(update.callback_query.from_user.id)
            return
        if update.callback_query.from_user.id in mathdata.answeredwrong:
            update.callback_query.answer('You thought you can correct ur answer? Jokes on you!')
            return
        if update.callback_query.from_user.id in mathdata.gotanswer:
            update.callback_query.answer('You seriously thought you could cheat on question? No, noob.')
            return
        if update.callback_query.data == 'mathquiz_wrong':
            update.callback_query.answer('Wrong.')
            mathdata.answeredwrong.append(update.callback_query.from_user.id)
            return
        if update.callback_query.data.startswith('mathquiz_correct'):
            name = update.callback_query.from_user.first_name
            if update.callback_query.from_user.last_name is not None:
                name += ' ' + update.callback_query.from_user.last_name
            if update.callback_query.from_user.username is not None:
                name += f' (@{update.callback_query.from_user.username})'
            update.callback_query.message.edit_text(update.callback_query.message.text +
                                                    ' ' +
                                                    update.callback_query.data.replace('mathquiz_correct', '') +
                                                    f'\n\nAnswered by {name}')
            data.ongoingmathq.pop(update.callback_query.message.chat.id)
            update.callback_query.answer('Your answer is correct! Good job!')
            return
    if update.callback_query.data in jokes.keys():
        texts = ['', '', '', '',
                 '\n\nLike the jokes? contact @quebeh200 (the creator of me) to request more jokes!',
                 '', '', '', '', '']
        update.callback_query.edit_message_text(
            f'{jokes[update.callback_query.data]["start"]}\n{jokes[update.callback_query.data]["end"]}{choice(texts)}',
            parse_mode='HTML'
        )


def inlinequery(update: Update, context):
    if update.inline_query.query.lower() == 'super idol':
        results = [
            InlineQueryResultArticle(
                id=str(uuid4()),
                title="Super idol (ori)",
                input_message_content=InputTextMessageContent(
                    "Super Idol\u7684\u7b11\u5bb9.\u90fd\u6ca1\u4f60\u7684\u751c.\u516b\u6708\u6b63\u5348\u7684\u9633"
                    "\u5149.\u90fd\u6ca1\u4f60\u8000\u773c.\u70ed\u7231 105 \xb0C\u7684\u4f60.\u6ef4\u6ef4\u6e05\u7eaf"
                    "\u7684\u84b8\u998f\u6c34.\u4f60\u4e0d\u77e5\u9053\u4f60\u6709\u591a\u53ef\u7231.\u8dcc\u5012\u540e"
                    "\u4f1a\u50bb\u7b11\u7740\u518d\u7ad9\u8d77\u6765.\u4f60\u4ece\u6765\u90fd\u4e0d\u8f7b\u8a00\u5931"
                    "\u8d25.\u5bf9\u68a6\u60f3\u7684\u6267\u7740\u4e00\u76f4\u4e0d\u66fe\u66f4\u6539.\u5f88\u5b89\u5fc3"
                    " \u5f53\u4f60\u5bf9\u6211\u8bf4.\u4e0d\u6015\u6709\u6211\u5728.\u653e\u7740\u8ba9\u6211\u6765."
                    "\u52c7\u6562\u8ffd\u81ea\u5df1\u7684\u68a6\u60f3.\u90a3\u575a\u5b9a\u7684\u6a21\u6837.Super Idol"
                    "\u7684\u7b11\u5bb9.\u90fd\u6ca1\u4f60\u7684\u751c.\u516b\u6708\u6b63\u5348\u7684\u9633\u5149."
                    "\u90fd\u6ca1\u4f60\u8000\u773c.\u70ed\u7231 105 \xb0C\u7684\u4f60.\u6ef4\u6ef4\u6e05\u7eaf\u7684"
                    "\u84b8\u998f\u6c34.\u5728\u8fd9\u72ec\u4e00\u65e0\u4e8c.\u5c5e\u4e8e\u6211\u7684\u65f6\u4ee3."
                    "\u4e0d\u6015\u5931\u8d25\u6765\u4e00\u573a.\u75db\u5feb\u7684\u70ed\u7231.\u70ed\u7231 105\xb0C"
                    "\u7684\u4f60.\u6ef4\u6ef4\u6e05\u7eaf\u7684\u84b8\u998f\u6c34.\u5728\u8fd9\u72ec\u4e00\u65e0\u4e8c"
                    ".\u5c5e\u4e8e\u6211\u7684\u65f6\u4ee3.\u83ab\u5fd8\u4e86\u521d\u5fc3\u5e38\u5728.\u75db\u5feb"
                    "\u53bb\u70ed\u7231.\u70ed\u7231 105\xb0C\u7684\u4f60.\u6ef4\u6ef4\u6e05\u7eaf\u7684\u84b8\u998f"
                    "\u6c34.\u559d\u4e00\u53e3\u53c8\u6d3b\u529b\u5168\u5f00.\u518d\u6b21\u56de\u5230\u6700\u4f73\u72b6"
                    "\u6001.\u559d\u4e00\u53e3\u54df.\u4f60\u4e0d\u77e5\u9053\u4f60\u6709\u591a\u53ef\u7231.\u8dcc"
                    "\u5012\u540e\u4f1a\u50bb\u7b11\u7740\u518d\u7ad9\u8d77\u6765.\u4f60\u4ece\u6765\u90fd\u4e0d\u8f7b"
                    "\u8a00\u5931\u8d25.\u5bf9\u68a6\u60f3\u7684\u6267\u7740\u4e00\u76f4\u4e0d\u66fe\u66f4\u6539.\u5f88"
                    "\u5b89\u5fc3 \u5f53\u4f60\u5bf9\u6211\u8bf4.\u4e0d\u6015\u6709\u6211\u5728.\u653e\u7740\u8ba9"
                    "\u6211\u6765.\u52c7\u6562\u8ffd\u81ea\u5df1\u7684\u68a6\u60f3.\u90a3\u575a\u5b9a\u7684\u6a21\u6837"
                    ".Super Idol\u7684\u7b11\u5bb9.\u90fd\u6ca1\u4f60\u7684\u751c.\u516b\u6708\u6b63\u5348\u7684\u9633"
                    "\u5149.\u90fd\u6ca1\u4f60\u8000\u773c.\u70ed\u7231 105\xb0C\u7684\u4f60.\u6ef4\u6ef4\u6e05\u7eaf"
                    "\u7684\u84b8\u998f\u6c34.\u5728\u8fd9\u72ec\u4e00\u65e0\u4e8c.\u5c5e\u4e8e\u6211\u7684\u65f6\u4ee3"
                    ".\u4e0d\u6015\u5931\u8d25\u6765\u4e00\u573a.\u75db\u5feb\u7684\u70ed\u7231.\u70ed\u7231 105\xb0C"
                    "\u7684\u4f60.\u6ef4\u6ef4\u6e05\u7eaf\u7684\u84b8\u998f\u6c34.\u5728\u8fd9\u72ec\u4e00\u65e0\u4e8c"
                    ".\u5c5e\u4e8e\u6211\u7684\u65f6\u4ee3.\u83ab\u5fd8\u4e86\u521d\u5fc3\u5e38\u5728.\u75db\u5feb"
                    "\u53bb\u70ed\u7231.\u70ed\u7231 105\xb0C\u7684\u4f60.\u6ef4\u6ef4\u6e05\u7eaf\u7684\u84b8\u998f"
                    "\u6c34.\u559d\u4e00\u53e3\u53c8\u6d3b\u529b\u5168\u5f00.\u518d\u6b21\u56de\u5230\u6700\u4f73\u72b6"
                    "\u6001.\u559d\u4e00\u53e3\u53c8\u6d3b\u529b\u5168\u5f00")
            )
        ]
        update.inline_query.answer(results)
        return
    _id = choice(list(jokes.keys()))
    results = [
        InlineQueryResultArticle(
            id=str(uuid4()),
            title="Joke",
            input_message_content=InputTextMessageContent(jokes[_id]['start']),
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(jokes[_id]['btn'] if 'btn' in jokes[_id].keys() else 'Why?', callback_data=_id)]])
        ),
        InlineQueryResultArticle(
            id=str(uuid4()),
            title="Funi Kid",
            input_message_content=InputTextMessageContent(
                'FUNI KIDD \U0001f602\U0001f602\U0001f602\U0001f602\U0001f602\U0001f602\U0001f631\U0001f976\U0001f602\U0001f631\U0001f602\U0001f631\U0001f929\U0001f631\U0001f929\U0001f975\U0001f6d0\U0001f976\U0001f976\U0001f631\U0001f602\U0001f929\U0001f929\U0001f631\U0001f631\U0001f602\U0001f631\U0001f602\U0001f631\U0001f929\U0001f6d0\U0001f6d0\U0001f64f\U0001f921\U0001f921\U0001f921\U0001f921\U0001f921\U0001f602\U0001f602'),
        ),
        InlineQueryResultArticle(
            id=str(uuid4()),
            title="What're u gonna do?",
            input_message_content=InputTextMessageContent(
                'WHAT ARE YOU GONNA DO ABOUT IT??? \u261d\ufe0f\u261d\ufe0f\U0001f923\U0001f923\U0001f602\U0001f602\U0001f643\U0001f636\U0001f600\U0001f602\U0001f602\U0001f601\U0001f5ff\U0001f631\U0001f631'
            )
        )
    ]

    update.inline_query.answer(results, cache_time=0)

