"""
Join link → mute → stop client delay
"""

from ...actions.join_leave import (
    JoinLeaveManager
)

from ...actions.auto_mute import (
    AutoMuteManager
)

from ...core.delay_engine import (
    delay_engine
)


class MuteAfterJoinHandler:

    def __init__(self, runner):
        self.runner = runner

    # ---------------------------------
    async def handle(self, message):

        try:
            link = message.text.split(
                " ",
                1
            )[1]

        except IndexError:

            return await message.reply_text(
                "Usage:\nmute <link>"
            )

        async def action(phone, app):

            joiner = JoinLeaveManager(
                app,
                phone
            )

            muter = AutoMuteManager(
                app,
                phone
            )

            joined = await joiner.join(link)

            if joined:

                await muter.mute(
                    link,
                    hours=None
                )

        await self.runner.run_action(action)

        # stop delay engine cycle
        delay_engine.reset()

        await message.reply_text(
            "Joined + muted"
        )
