from pyrogram.errors import FloodWait

from core.safe_executor import SafeExecutor
from core.delay_engine import delay_engine
from core.flood_handler import flood_handler
from core.logger import get_action_logger


class MediaSender:

    def __init__(self, client, session):

        self.client = client
        self.session = session
        self.log = get_action_logger(
            "media_sender",
            session
        )

    async def _exec(
        self,
        chat,
        file,
        media_type,
        caption,
        silent
    ):

        if media_type == "photo":

            await self.client.send_photo(
                chat,
                file,
                caption=caption,
                disable_notification=silent
            )

        elif media_type == "video":

            await self.client.send_video(
                chat,
                file,
                caption=caption,
                disable_notification=silent
            )

        elif media_type == "document":

            await self.client.send_document(
                chat,
                file,
                caption=caption,
                disable_notification=silent
            )

    async def send(
        self,
        chat_id,
        file_path,
        media_type="photo",
        caption=None,
        silent=True
    ):

        try:

            await delay_engine.message_delay()

            await SafeExecutor.run(
                self._exec(
                    chat_id,
                    file_path,
                    media_type,
                    caption,
                    silent
                ),
                self.session,
                "media_send"
            )

            self.log.info(
                f"Media → {chat_id}"
            )

            return True

        except FloodWait as e:

            self.log.warning(
                f"Flood {e.value}s"
            )

            await flood_handler.handle(
                e,
                self.session,
                "media_send"
            )

        except Exception as e:

            self.log.exception(e)

        return False
