import logging

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

from classes.callbacks import CallbackLanguage
from classes.pyroclient import PyroClient
from modules.utils import is_permitted

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 app.find_group(message.chat.id)
    locale = group.select_locale(app, message.from_user)

    if not (await is_permitted(app, group, message=message)):
        await message.reply_text(
            app._("permission_denied", "messages", locale=locale), quote=True
        )
        return

    keyboard = InlineKeyboard(row_width=2)
    buttons = [
        InlineButton(f"{data['flag']} {data['name']}", f"language:{language}")
        for language, data in app.in_every_locale("metadata").items()
        if data["selectable"]
    ]
    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 app.find_group(callback.message.chat.id)
    locale = group.select_locale(app, callback.message.from_user)

    if not (await is_permitted(app, group, callback=callback)):
        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,
    )
