import logging

from pykeyboard import InlineButton, InlineKeyboard
from pyrogram import filters
from pyrogram.client import Client
from pyrogram.enums.chat_member_status import ChatMemberStatus
from pyrogram.types import CallbackQuery, Message

from classes.callbacks import CallbackLanguage
from classes.pyroclient import PyroClient
from classes.pyrogroup import PyroGroup

logger = logging.getLogger(__name__)


@PyroClient.on_message(
    ~filters.scheduled & filters.group & filters.command(["language"], prefixes=["/"])  # type: ignore
)
async def command_language(app: PyroClient, message: Message):
    group = await PyroGroup.create_if_not_exists(message.chat.id, None, True)
    locale = group.select_locale(app, message.from_user)

    if (await app.get_chat_member(group.id, message.from_user.id)).status not in [
        ChatMemberStatus.ADMINISTRATOR,
        ChatMemberStatus.OWNER,
    ]:
        await message.reply_text(
            app._("permission_denied", "messages", locale=locale), quote=True
        )
        return

    keyboard = InlineKeyboard(row_width=2)
    buttons = []

    for language, data in app.in_every_locale("metadata").items():
        if data["selectable"]:
            buttons.append(
                InlineButton(f"{data['flag']} {data['name']}", f"language;{language}")
            )

    buttons.append(
        InlineButton(
            f"🤖 {app._('locale_default', 'buttons', locale=locale)}", "language;default"
        )
    )

    keyboard.add(*buttons)

    await message.reply_text(
        app._("locale_choice", "messages", locale=locale),
        reply_markup=keyboard,
    )


@Client.on_callback_query(filters.regex(r"language;[\s\S]*"))  # type: ignore
async def callback_language(app: PyroClient, callback: CallbackQuery):
    group = await PyroGroup.create_if_not_exists(callback.message.chat.id, None, True)
    locale = group.select_locale(app, callback.message.from_user)

    if (await app.get_chat_member(group.id, callback.from_user.id)).status not in [
        ChatMemberStatus.ADMINISTRATOR,
        ChatMemberStatus.OWNER,
    ]:
        await callback.answer(
            app._("wrong_user", "callbacks", locale=locale), show_alert=True
        )
        return

    parsed = CallbackLanguage.from_callback(callback)

    logger.info(
        "Locale of group %s has been set to %s (auto: %s)",
        group.id,
        parsed.language,
        group.locale_auto,
    )

    if parsed.language == "default":
        await group.set_locale(None)
        await callback.answer(
            app._("locale_set", "callbacks", locale=app.default_locale).format(
                locale=app._("locale_default", "buttons", locale=locale)
            ),
            show_alert=True,
        )
        return

    await group.set_locale(parsed.language)
    await callback.answer(
        app._("locale_set", "callbacks", locale=parsed.language).format(
            locale=app._("name", "metadata", locale=parsed.language)
        ),
        show_alert=True,
    )
