from pyrogram.errors import FloodWait, RPCError

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 BioChanger:

    MAX_LENGTH = 70

    def __init__(self, client, session_name):

        self.client = client
        self.session = session_name
        self.log = get_action_logger(
            "change_bio",
            session_name
        )

    async def _exec(self, bio):

        await self.client.update_profile(
            bio=bio
        )

    async def change(self, bio: str):

        try:

            if len(bio) > self.MAX_LENGTH:
                raise ValueError(
                    "Bio too long"
                )

            await delay_engine.profile_delay()

            await SafeExecutor.run(
                self._exec(bio),
                self.session,
                "change_bio"
            )

            self.log.info(
                f"Bio updated → {bio}"
            )

            return True

        except FloodWait as e:

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

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

        except RPCError as e:

            self.log.error(f"RPC → {e}")

        except Exception as e:

            self.log.exception(
                f"Error → {e}"
            )

        return False
