from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ForceReply
from var import bannedids, jokes, bot
from random import choice, randint
from PIL import Image
from io import BytesIO
from json import dumps
from memer import make as makememe
import data

emojis = [i for i in '💄💅😩🥶🤓💝🥱😏🗿😡😩🥵🥸🙈']

def makelist(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.text.lower() in ('/makelist', '/makelist@spacethebot'):
        update.message.reply_text(
            'Usage: /makelist <title>\nTo add a point, use /add replying to the list message.')
        return
    text = update.message.text[len('/makelist@spacethebot '):] \
        if update.message.text.lower().startswith('/makelist@spacethebot') \
        else update.message.text[len('/makelist '):]
    bot.sendMessage(update.message.chat.id, 'List\n' + text)

def to512pxc(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.reply_to_message is not None:
        if len(update.message.reply_to_message.photo) > 0:
            fileid = update.message.reply_to_message.photo[len(update.message.reply_to_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 sticker is done, forward it to @stickers bot after using '
                '/addsticker command to add it to your pack.'
            )
            return
    if update.message.from_user.id in data.pending_512pic:
        update.message.reply_text('Waiting for the photo...')
        return
    data.pending_512pic.append(update.message.from_user.id)
    update.message.reply_text('Send the photo...', reply_markup=ForceReply(selective=True))
    return

def joke(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    _id = choice(list(jokes.keys()))
    text = jokes[_id]['btn'] if 'btn' in jokes[_id].keys() else 'Why?'
    kb = InlineKeyboardMarkup([[InlineKeyboardButton(text, callback_data=_id)]])
    update.message.reply_text(jokes[_id]['start'], reply_markup=kb)

def joke_add(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.from_user.id == 1341877177:
        pass
    else:
        update.message.reply_text('Sorry you cant do that XD')
        return
    params = update.message.text
    if params.__contains__('/addjoke@SpaceTheBot'):
        params = params.replace('/addjoke@SpaceTheBot ', '')
    else:
        params = params.replace('/addjoke ', '')
    params = params.split(';')
    if len(params) < 2:
        update.message.reply_text('Too few args.')
        return
    keys = list(jokes.keys())
    num = int(keys[len(keys) - 1].replace('j_id', ''))
    key = 'j_id' + str(num + 1)
    if len(params) == 2:
        jokes[key] = {'start': params[0], 'end': params[1]}
    if len(params) == 3:
        jokes[key] = {'start': params[0], 'end': params[1], 'btn': params[2]}
    with open('jokes.json', 'w') as f:
        f.write(dumps(jokes, indent=2))
    if len(params) == 3:
        btntxt = params[2]
    else:
        btntxt = 'Why?'
    update.message.reply_text(
        jokes[key]['start'],
        reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(btntxt, callback_data=key)]])
    )

def jokes_(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.from_user.id != 1341877177:
        update.message.reply_text('You cant do this, only the developer can xD')
        return
    update.message.reply_document(open('jokes.json'), caption='May the jokes be with you.')
    return

def choose(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.text.lower().startswith('/choose@spacethebot '):
        update.message.text = update.message.text[20:]
    elif update.message.text.lower().startswith('/choose '):
        update.message.text = update.message.text[8:]
    text = update.message.text.split(',')
    if len(text) < 2:
        update.message.reply_text('Usage : /choose <option1>,<option2>\nCan take as much options as you want.')
        return
    text = choice(text)
    update.message.reply_text(text)

def shuffle(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.text.lower().startswith('/shuffle@spacethebot '):
        update.message.text = update.message.text[21:]
    elif update.message.text.lower().startswith('/shuffle '):
        update.message.text = update.message.text[9:]
    text = update.message.text.split(',')
    if len(text) < 2:
        update.message.reply_text('Usage : /shuffle <item1>,<item2>\nCan take as much items as you want.')
        return
    shuffle(text)
    tmp = ''
    for i in range(len(text)):
        tmp += f'\n{i + 1}. {text[i]}'
    update.message.reply_text(tmp)

def mathq(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.chat.id in data.ongoingmathq.keys():
        mathdata = data.ongoingmathq[update.message.chat.id]
        bot.editMessageText(f'Question:\n{mathdata.latestn1} + {mathdata.latestn2} + '
                            f'{mathdata.latestn3} = {mathdata.latestanswer}'
                            f'\n\nNew /mathquiz command executed.', mathdata.latestchatid, mathdata.latestmsgid)
    n1 = randint(1, 100)
    n2 = randint(1, 100)
    n3 = randint(1, 100)
    answer = n1 + n2 + n3
    answerbtn = 0
    tmp = [-25, -20, -15, -10, -5, 5, 10, 15, 20, 25]
    judge = ['r', 'a', 'r', 'r']
    btns = {}
    for i in range(4):
        con = choice(judge)
        judge.remove(con)
        if con != 'a':
            num = choice(tmp)
            tmp.remove(num)
            btns[f'btn{i + 1}'] = num
        if con == 'a':
            answerbtn = f'btn{i + 1}'
            btns[f'btn{i + 1}'] = 0
    btnobjs = {}
    for i in btns.keys():
        btnobjs[i] = InlineKeyboardButton(str(btns[i] + answer), callback_data='mathquiz_wrong')
        if i == answerbtn:
            btnobjs[i].callback_data = f'mathquiz_correct{n1 + n2 + n3}'
    kb = InlineKeyboardMarkup(
        [
            [btnobjs['btn1'], btnobjs['btn2']],
            [btnobjs['btn3'], btnobjs['btn4']],
            [InlineKeyboardButton('Answer (for noobs)', callback_data='mathquiz_getanswer')],
            [InlineKeyboardButton('End question', callback_data='mathquiz_stopquestion')]
        ]
    )
    msg = update.message.reply_text(f'Question:\n{n1} + {n2} + {n3} = ', reply_markup=kb)
    mathdata = data.mathquiz()
    mathdata.latestn1 = n1
    mathdata.latestn2 = n2
    mathdata.latestn3 = n3
    mathdata.latestanswer = answer
    mathdata.latestmsgid = msg.message_id
    mathdata.latestchatid = msg.chat.id
    data.ongoingmathq[update.message.chat.id] = mathdata
    return

def addtexts(update: Update, context):
    if update.message.from_user.id in bannedids:
        return
    if update.message.text.lower() in ('/addtexts', '/addtexts@spacethebot'):
        update.message.reply_text('Usage : /addtexts <text1>;<text2:optional>\n'
                                  'Recommended to have an image no less then 500 and no more than 600 pixels.\n'
                                  'or use /to512pic command before using this one.')
        return
    if update.message.reply_to_message is not None:
        if len(update.message.reply_to_message.photo) > 0:
            fileid = update.message.reply_to_message.photo[len(update.message.reply_to_message.photo) - 1].file_id
            m = update.message.reply_text('Processing image...')
            file = bot.getFile(fileid)
            io = BytesIO()
            io.write(file.download_as_bytearray())
            params = update.message.text.split(' ')
            if params[0] == '/addtexts':
                update.message.text = update.message.text[10:]
            else:
                update.message.text = update.message.text[22:]
            params = update.message.text.split(';')
            if len(params) == 1:
                params.insert(1, '')
            update.message.reply_photo(makememe(io, params[0], params[1]))
            m.edit_text('Text processing is done.')
            return
    if update.message.from_user.id in data.pending_addtext:
        update.message.reply_text('Waiting for the photo...')
        return
    params = update.message.text.split(' ')
    if params[0] == '/addtexts':
        update.message.text = update.message.text[10:]
    else:
        update.message.text = update.message.text[22:]
    params = update.message.text.split(';')
    if len(params) == 1:
        params.insert(1, '')
    data.pending_addtext.append(update.message.from_user.id)
    data.pending_addtextdata[str(update.message.from_user.id)] = params
    update.message.reply_text('Send the photo...', reply_markup=ForceReply(selective=True))
    return

def slip(update: Update, context):
    t = ''
    for i in update.message.text.split(' ')[1:]:
        t += i
        t += choice(emojis)
    update.message.reply_text(t)
