import logging

from pyrogram import filters
from pyrogram.types import (
    CallbackQuery,
    ChatPermissions,
    InlineKeyboardButton,
    InlineKeyboardMarkup,
    Message,
)

from classes.callbacks import CallbackEmoji
from classes.pyroclient import PyroClient

logger = logging.getLogger(__name__)


@PyroClient.on_callback_query(filters.regex(r"emoji:[\s\S]*"))  # type: ignore
async def callback_emoji_button(app: PyroClient, callback: CallbackQuery):
    parsed = CallbackEmoji.from_callback(callback)
    group = await app.find_group(callback.message.chat.id)
    locale = group.select_locale(app, callback.message.from_user)

    if callback.from_user.id != parsed.user_id:
        await callback.answer(
            app._("wrong_user", "callbacks", locale=locale), show_alert=True
        )
        return

    user = await app.find_user(callback.from_user, group.id)

    logger.debug(
        "User %s has pressed the %s emoji '%s'",
        user.id,
        "correct" if parsed.emoji in user.emojis else "wrong",
        parsed.emoji,
    )

    if parsed.emoji in user.selected:
        await callback.answer()
        return

    await user.update_selected(parsed.emoji)

    if parsed.emoji in user.emojis:
        await user.update_score(1)

        if user.score >= 5:
            logger.info("User %s has passed the captcha", user.id)

            await callback.message.delete()
            await callback.answer(
                app._("captcha_passed", "callbacks", locale=locale), show_alert=True
            )
            await app.send_message(
                group.id,
                app._("welcome", "messages", locale=locale).format(
                    mention=callback.from_user.mention
                ),
            )
            await app.restrict_chat_member(
                chat_id=group.id,
                user_id=callback.from_user.id,
                permissions=callback.message.chat.permissions,
            )
            return

        logger.info(
            "User %s has chosen correctly and needs to select %s more emoji(s)",
            user.id,
            5 - user.score,
        )

        emoji_placeholder = "✅"
    else:
        if user.mistakes >= 2:
            logger.info("User %s has failed the captcha", user.id)

            await user.set_failed(True)
            await callback.answer(
                app._("captcha_failed", "callbacks", locale=locale), show_alert=True
            )

            if group.ban_failed:
                banned = await app.ban_chat_member(group.id, callback.from_user.id)

                if isinstance(banned, Message):
                    await banned.delete()

            await callback.message.delete()
            return

        await user.update_mistakes(1)
        logger.info(
            "User %s has made a mistake and has %s attempt(s) left",
            user.id,
            2 - user.mistakes,
        )

        await callback.answer(
            app._("captcha_mistake", "callbacks", locale=locale).format(
                remaining=2 - user.mistakes
            ),
            show_alert=True,
        )

        emoji_placeholder = "🛑"

    button_replace = (0, 0)

    for row_index, row in enumerate(callback.message.reply_markup.inline_keyboard):
        for button_index, button in enumerate(row):
            if button.text == parsed.emoji:
                button_replace = (row_index, button_index)

    new_keyboard = callback.message.reply_markup.inline_keyboard
    new_keyboard[button_replace[0]][button_replace[1]] = InlineKeyboardButton(
        emoji_placeholder, "nothing"
    )

    await callback.edit_message_reply_markup(
        reply_markup=InlineKeyboardMarkup(new_keyboard)
    )
