from datetime import datetime, timedelta

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

    def __init__(self, client, session):

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

    async def _exec(self, chat, hours):

        if hours is None:
            until = datetime.utcnow() + timedelta(days=3650)
        else:
            until = datetime.utcnow() + timedelta(hours=hours)

        await self.client.mute_chat(
            chat,
            until_date=until
        )

    async def mute(
        self,
        chat,
        hours=None
    ):

        try:

            await delay_engine.join_delay()

            await SafeExecutor.run(
                self._exec(chat, hours),
                self.session,
                "mute"
            )

            self.log.info(
                f"Muted → {chat}"
            )

            return True

        except FloodWait as e:

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

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

        except Exception as e:

            self.log.exception(e)

        return False
