import logging

from pyrogram import filters
from pyrogram.enums.chat_member_status import ChatMemberStatus
from pyrogram.types import Message

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_auto"], prefixes=["/"])  # type: ignore
)
async def command_language_auto(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

    if group.locale_auto:
        await message.reply_text(
            app._("locale_auto_disabled", "messages", locale=locale).format(
                default_locale=f"{app._('flag', 'metadata', locale=app.default_locale)} {app._('name', 'metadata', locale=app.default_locale)}"
            )
        )
    else:
        await message.reply_text(
            app._("locale_auto_enabled", "messages", locale=locale).format(
                default_locale=f"{app._('flag', 'metadata', locale=app.default_locale)} {app._('name', 'metadata', locale=app.default_locale)}"
            )
        )

    logger.info(
        "Automatic locale selection of group %s has been set to %s (group: %s)",
        group.id,
        not group.locale_auto,
        group.locale,
    )

    await group.set_locale_auto(not group.locale_auto)
