from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters, InlineQueryHandler, \
    CallbackContext, CallbackQueryHandler
import logging

from tgbot.config import TOKEN
from tgbot.shit.handlers import handle_xitter, handle_red_ebalo, handle_hentai, handle_cute_button
from tgbot.shit.render import render_text_on_image, image_to_string
from io import BytesIO

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await context.bot.send_message(chat_id=update.effective_chat.id,
                                   text='WE ARE A PARTY OF UTTER MADNESS, '
                                        'AND I AM A PERSON OF COMPLETE AND TOTAL DELUSION!')


async def respond_with_picture(update: Update, context: ContextTypes.DEFAULT_TYPE):
    file = render_text_on_image("tgbot/assets/red_ebalo.png", update.message.text)
    await context.bot.send_sticker(chat_id=update.effective_chat.id, sticker=file)


async def image2string(update: Update, context: ContextTypes.DEFAULT_TYPE):
    photo = update.message.photo[-1]

    file = await photo.get_file()
    bio = BytesIO()
    await file.download_to_memory(out=bio)

    bio.seek(0)

    s = image_to_string(bio)

    await update.message.reply_text(s)


async def callback_query_handler(update: Update, context: CallbackContext):
    query = update.callback_query

    if query.data == "show_cute_popup":
        await context.bot.answer_callback_query(
            callback_query_id=query.id,
            text="Hey! This button is for you! Thank you for clicking it, you are awesome!",
            show_alert=True
        )

    else:
        await query.answer()


async def handle_inline(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.inline_query.query
    if not query:
        return

    if "https://x.com" in query:
        await handle_xitter(update, context)
        return

    if query.startswith("hentai"):
        await handle_hentai(update, context)
        return

    if query.startswith("button!"):
        await handle_cute_button(update, context)
        return

    await handle_red_ebalo(update, context)


def main():
    application = ApplicationBuilder().token(TOKEN).build()

    start_handler = CommandHandler('start', start)
    picture_handler = MessageHandler(filters.TEXT & ~filters.COMMAND, respond_with_picture)

    application.add_handler(start_handler)

    application.add_handler(MessageHandler(filters.PHOTO, image2string))
    application.add_handler(picture_handler)
    application.add_handler(InlineQueryHandler(handle_inline))
    application.add_handler(CallbackQueryHandler(callback_query_handler))

    application.run_polling()


if __name__ == '__main__':
    main()
