#  PyroRatnaGram - Telegram MTProto API Client Library for Python
#  Copyright (C) 2017-present Dan <https://github.com/delivrance>
#  Copyright (C) 2022-present AnmolRatna25 <https://github.com/AnmolRatna25>
#
#  This file is part of PyroRatnaGram.
#
#  PyroRatnaGram is free software: you can redistribute it and/or modify
#  it under the terms of the GNU Lesser General Public License as published
#  by the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  PyroRatnaGram is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Lesser General Public License for more details.
#
#  You should have received a copy of the GNU Lesser General Public License
#  along with PyroRatnaGram.  If not, see <http://www.gnu.org/licenses/>.

from pyrogram import enums, raw, types
from ..object import Object
from typing import Optional, Union

class KeyboardButton(Object):
    """One button of the reply keyboard.
    For simple text buttons String can be used instead of this object to specify text of the button.
    Optional fields are mutually exclusive.

    Parameters:
        text (``str``):
            Text of the button. If none of the optional fields are used, it will be sent as a message when
            the button is pressed.

        request_contact (``bool``, *optional*):
            If True, the user's phone number will be sent as a contact when the button is pressed.
            Available in private chats only.

        request_location (``bool``, *optional*):
            If True, the user's current location will be sent when the button is pressed.
            Available in private chats only.

        request_chat (:obj:`~pyrogram.types.RequestPeerTypeChannel` | :obj:`~pyrogram.types.RequestPeerTypeChat`, *optional*):
            If specified, defines the criteria used to request a suitable chats/channels.
            The identifier of the selected chats will be shared with the bot when the corresponding button is pressed.

        request_user (:obj:`~pyrogram.types.RequestPeerTypeUser`, *optional*):
            If specified, defines the criteria used to request a suitable users.
            The identifier of the selected users will be shared with the bot when the corresponding button is pressed.

        web_app (:obj:`~pyrogram.types.WebAppInfo`, *optional*):
            If specified, the described `Web App <https://core.telegram.org/bots/webapps>`_ will be launched when the
            button is pressed. The Web App will be able to send a “web_app_data” service message. Available in private
            chats only.
        copy_text (``str``, *optional*):
            If specified, pressing the button will copy this text to the clipboard.

        request_poll (:obj:`~pyrogram.enums.PollType`, *optional*):
            If specified, the user will be asked to create a poll.
            Pass :obj:`~pyrogram.enums.PollType.QUIZ` to request a quiz, :obj:`~pyrogram.enums.PollType.REGULAR`
            to request a regular poll, or omit the type to allow the user to choose.

        icon_custom_emoji_id (``int`` | ``str``, *optional*):
            Unique identifier of the custom emoji shown before the button text.

        style (:obj:`~pyrogram.enums.ButtonStyle`, *optional*):
            Visual style of the button. One of PRIMARY (blue), DANGER (red), SUCCESS (green).
    """

    def __init__(
        self,
        text: str,
        request_contact: bool = None,
        request_location: bool = None,
        request_chat: Union["types.RequestPeerTypeChat","types.RequestPeerTypeChannel"] = None,
        request_user: "types.RequestPeerTypeUser" = None,
        web_app: "types.WebAppInfo" = None,
        copy_text: Optional[str] = None,
        request_poll: Optional["enums.PollType"] = None,
        icon_custom_emoji_id: Optional[Union[int, str]] = None,
        style: Optional["enums.ButtonStyle"] = None
    ):
        super().__init__()

        self.text = str(text)
        self.request_contact = request_contact
        self.request_location = request_location
        self.request_chat = request_chat
        self.request_user = request_user
        self.web_app = web_app
        self.copy_text = copy_text
        self.request_poll = request_poll
        self.icon_custom_emoji_id = int(icon_custom_emoji_id) if icon_custom_emoji_id is not None else None
        self.style = style

    @staticmethod
    def _build_raw_style(style, icon_custom_emoji_id):
        """Build raw.types.KeyboardButtonStyle from high-level params."""
        if style is None and icon_custom_emoji_id is None:
            return None
        icon_id = int(icon_custom_emoji_id) if icon_custom_emoji_id is not None else None
        return raw.types.KeyboardButtonStyle(
            bg_primary=True if style == enums.ButtonStyle.PRIMARY else None,
            bg_danger=True if style == enums.ButtonStyle.DANGER else None,
            bg_success=True if style == enums.ButtonStyle.SUCCESS else None,
            icon=icon_id
        )

    @staticmethod
    def _parse_raw_style(raw_style):
        """Parse raw.types.KeyboardButtonStyle into (ButtonStyle enum, icon_id)."""
        if raw_style is None:
            return None, None
        style = None
        if getattr(raw_style, 'bg_primary', False):
            style = enums.ButtonStyle.PRIMARY
        elif getattr(raw_style, 'bg_danger', False):
            style = enums.ButtonStyle.DANGER
        elif getattr(raw_style, 'bg_success', False):
            style = enums.ButtonStyle.SUCCESS
        icon = getattr(raw_style, 'icon', None)
        return style, icon

    @staticmethod
    def read(b):
        if isinstance(b, raw.types.KeyboardButton):
            style, icon = KeyboardButton._parse_raw_style(getattr(b, 'style', None))
            if style is None and icon is None:
                return b.text
            return KeyboardButton(text=b.text, style=style, icon_custom_emoji_id=icon)

        if isinstance(b, raw.types.KeyboardButtonRequestPhone):
            style, icon = KeyboardButton._parse_raw_style(getattr(b, 'style', None))
            return KeyboardButton(
                text=b.text,
                request_contact=True,
                style=style,
                icon_custom_emoji_id=icon
            )

        if isinstance(b, raw.types.KeyboardButtonRequestGeoLocation):
            style, icon = KeyboardButton._parse_raw_style(getattr(b, 'style', None))
            return KeyboardButton(
                text=b.text,
                request_location=True,
                style=style,
                icon_custom_emoji_id=icon
            )

        if isinstance(b, raw.types.KeyboardButtonSimpleWebView):
            style, icon = KeyboardButton._parse_raw_style(getattr(b, 'style', None))
            return KeyboardButton(
                text=b.text,
                web_app=types.WebAppInfo(url=b.url),
                style=style,
                icon_custom_emoji_id=icon
            )

        if isinstance(b, raw.types.KeyboardButtonCopy):
            style, icon = KeyboardButton._parse_raw_style(getattr(b, 'style', None))
            return KeyboardButton(
                text=b.text,
                copy_text=b.copy_text,
                style=style,
                icon_custom_emoji_id=icon
            )

        if isinstance(b, raw.types.KeyboardButtonRequestPoll):
            style, icon = KeyboardButton._parse_raw_style(getattr(b, 'style', None))
            quiz = getattr(b, 'quiz', None)
            if quiz is True:
                request_poll = enums.PollType.QUIZ
            elif quiz is False:
                request_poll = enums.PollType.REGULAR
            else:
                request_poll = None
            return KeyboardButton(
                text=b.text,
                request_poll=request_poll,
                style=style,
                icon_custom_emoji_id=icon
            )

        if isinstance(b, raw.types.KeyboardButtonRequestPeer):
            style, icon = KeyboardButton._parse_raw_style(getattr(b, 'style', None))
            if isinstance(b.peer_type, raw.types.RequestPeerTypeBroadcast):
                user_privileges = getattr(b.peer_type, "user_admin_rights", None)
                bot_privileges = getattr(b.peer_type, "bot_admin_rights", None)
                return KeyboardButton(
                    text=b.text,
                    request_chat=types.RequestPeerTypeChannel(
                        is_creator=b.peer_type.creator,
                        is_username=b.peer_type.has_username,
                        max=b.max_quantity,
                        user_privileges=user_privileges,
                        bot_privileges=bot_privileges
                    ),
                    style=style,
                    icon_custom_emoji_id=icon
                )
            if isinstance(b.peer_type, raw.types.RequestPeerTypeChat):
                user_privileges = getattr(b.peer_type, "user_admin_rights", None)
                bot_privileges = getattr(b.peer_type, "bot_admin_rights", None)
                return KeyboardButton(
                    text=b.text,
                    request_chat=types.RequestPeerTypeChat(
                        is_creator=b.peer_type.creator,
                        is_bot_participant=b.peer_type.bot_participant,
                        is_username=b.peer_type.has_username,
                        is_forum=b.peer_type.forum,
                        max=b.max_quantity,
                        user_privileges=user_privileges,
                        bot_privileges=bot_privileges
                    ),
                    style=style,
                    icon_custom_emoji_id=icon
                )
            if isinstance(b.peer_type, raw.types.RequestPeerTypeUser):
                return KeyboardButton(
                    text=b.text,
                    request_user=types.RequestPeerTypeUser(
                        is_bot=b.peer_type.bot,
                        is_premium=b.peer_type.premium,
                        max=b.max_quantity
                    ),
                    style=style,
                    icon_custom_emoji_id=icon
                )

    def write(self):
        raw_style = self._build_raw_style(self.style, self.icon_custom_emoji_id)

        if self.request_contact:
            return raw.types.KeyboardButtonRequestPhone(text=self.text, style=raw_style)
        elif self.request_location:
            return raw.types.KeyboardButtonRequestGeoLocation(text=self.text, style=raw_style)
        elif self.copy_text is not None:
            return raw.types.KeyboardButtonCopy(
                text=self.text,
                copy_text=self.copy_text,
                style=raw_style
            )
        elif self.request_poll is not None:
            if self.request_poll == enums.PollType.QUIZ:
                quiz = True
            elif self.request_poll == enums.PollType.REGULAR:
                quiz = False
            else:
                quiz = None
            return raw.types.KeyboardButtonRequestPoll(
                text=self.text,
                quiz=quiz,
                style=raw_style
            )
        elif self.request_chat:
            user_privileges = self.request_chat.user_privileges
            bot_privileges = self.request_chat.bot_privileges

            user_admin_rights = raw.types.ChatAdminRights(
                    change_info=user_privileges.can_change_info,
                    post_messages=user_privileges.can_post_messages,
                    post_stories=user_privileges.can_post_stories,
                    edit_messages=user_privileges.can_edit_messages,
                    edit_stories=user_privileges.can_post_stories,
                    delete_messages=user_privileges.can_delete_messages,
                    delete_stories=user_privileges.can_delete_stories,
                    ban_users=user_privileges.can_restrict_members,
                    invite_users=user_privileges.can_invite_users,
                    pin_messages=user_privileges.can_pin_messages,
                    add_admins=user_privileges.can_promote_members,
                    anonymous=user_privileges.is_anonymous,
                    manage_call=user_privileges.can_manage_video_chats,
                    other=user_privileges.can_manage_chat
            ) if user_privileges else None

            bot_admin_rights = raw.types.ChatAdminRights(
                    change_info=bot_privileges.can_change_info,
                    post_messages=bot_privileges.can_post_messages,
                    post_stories=bot_privileges.can_post_stories,
                    edit_messages=bot_privileges.can_edit_messages,
                    edit_stories=bot_privileges.can_post_stories,
                    delete_messages=bot_privileges.can_delete_messages,
                    delete_stories=bot_privileges.can_delete_stories,
                    ban_users=bot_privileges.can_restrict_members,
                    invite_users=bot_privileges.can_invite_users,
                    pin_messages=bot_privileges.can_pin_messages,
                    add_admins=bot_privileges.can_promote_members,
                    anonymous=bot_privileges.is_anonymous,
                    manage_call=bot_privileges.can_manage_video_chats,
                    other=bot_privileges.can_manage_chat
            ) if bot_privileges else None

            if isinstance(self.request_chat, types.RequestPeerTypeChannel):
                return raw.types.InputKeyboardButtonRequestPeer(
                    text=self.text,
                    button_id=self.request_chat.button_id,
                    peer_type=raw.types.RequestPeerTypeBroadcast(
                        creator=self.request_chat.is_creator,
                        has_username=self.request_chat.is_username,
                        user_admin_rights=user_admin_rights,
                        bot_admin_rights=bot_admin_rights
                    ),
                    max_quantity=self.request_chat.max,
                    name_requested=self.request_chat.is_name_requested,
                    username_requested=self.request_chat.is_username_requested,
                    photo_requested=self.request_chat.is_photo_requested,
                    style=raw_style
                )
            return raw.types.InputKeyboardButtonRequestPeer(
                text=self.text,
                button_id=self.request_chat.button_id,
                peer_type=raw.types.RequestPeerTypeChat(
                    creator=self.request_chat.is_creator,
                    bot_participant=self.request_chat.is_bot_participant,
                    has_username=self.request_chat.is_username,
                    forum=self.request_chat.is_forum,
                    user_admin_rights=user_admin_rights,
                    bot_admin_rights=bot_admin_rights
                ),
                max_quantity=self.request_chat.max,
                name_requested=self.request_chat.is_name_requested,
                username_requested=self.request_chat.is_username_requested,
                photo_requested=self.request_chat.is_photo_requested,
                style=raw_style
            )
        elif self.request_user:
            return raw.types.InputKeyboardButtonRequestPeer(
                text=self.text,
                button_id=self.request_user.button_id,
                peer_type=raw.types.RequestPeerTypeUser(
                    bot=self.request_user.is_bot,
                    premium=self.request_user.is_premium
                ),
                max_quantity=self.request_user.max,
                name_requested=self.request_user.is_name_requested,
                username_requested=self.request_user.is_username_requested,
                photo_requested=self.request_user.is_photo_requested,
                style=raw_style
            )
        elif self.web_app:
            return raw.types.KeyboardButtonSimpleWebView(
                text=self.text,
                url=self.web_app.url,
                style=raw_style
            )
        else:
            return raw.types.KeyboardButton(text=self.text, style=raw_style)
