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

    def __init__(self, client, session):

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

    async def _exec(self, first, last):

        await self.client.update_profile(
            first_name=first,
            last_name=last
        )

    async def change(
        self,
        first_name,
        last_name=""
    ):

        try:

            await delay_engine.profile_delay()

            await SafeExecutor.run(
                self._exec(
                    first_name,
                    last_name
                ),
                self.session,
                "change_name"
            )

            self.log.info(
                f"Name → {first_name} {last_name}"
            )

            return True

        except FloodWait as e:

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

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

        except Exception as e:

            self.log.exception(e)

        return False
