from AbhiCalls.yt import resolve_query
from AbhiCalls.models import Song
from AbhiCalls.player import Player

class VoiceController:
    def __init__(self, engine):
        self.engine = engine
        self.player = Player(engine)
        self.engine.on_end = self._on_end
        self.plugins = []

    def load_plugin(self, plugin):
        self.plugins.append(plugin)

    async def _hook(self, name, *args):
        for p in self.plugins:
            fn = getattr(p, name, None)
            if fn:
                try:
                    await fn(*args)
                except Exception as e:
                    print(f"[Plugin:{p.name}] {name} error:", e)

    async def play(self, chat_id, query, requested_by):
        results = await resolve_query(query)
        if not results:
            return None, None

        first_pos = None
        last_song = None

        for data in results:
            song = Song(
                title=data["title"],
                url=data["url"],
                duration=data["duration"],
                views=data["views"],
                stream=data["stream"],
                requested_by=requested_by,
            )

            pos = await self.player.play(chat_id, song)
            await self._hook("on_queue_add", chat_id, song, pos)

            if first_pos is None:
                first_pos = pos
            last_song = song

        if first_pos == 1:
            await self._hook("on_song_start", chat_id, last_song)

        return last_song, first_pos

    async def skip(self, chat_id):
        await self.player.skip(chat_id)

    async def previous(self, chat_id):
        return await self.player.previous(chat_id)

    async def pause(self, chat_id):
        await self.player.pause(chat_id)

    async def resume(self, chat_id):
        await self.player.resume(chat_id)

    async def stop(self, chat_id):
        await self.player.stop(chat_id)

    async def mute(self, chat_id):
        await self.player.mute(chat_id)

    async def unmute(self, chat_id):
        await self.player.unmute(chat_id)

    async def volume(self, chat_id, volume: int):
        await self.player.volume(chat_id, volume)
        

    def loop(self, chat_id, count=None):
        return self.player.set_loop(chat_id, count)

    def eta(self, chat_id):
        return self.player.eta(chat_id)

    async def _on_end(self, chat_id):
        q = self.player.queues.get(chat_id)
        song = q.current() if q else None
        if song:
            await self._hook("on_song_end", chat_id, song)

        await self.player.skip(chat_id)

        next_song = q.current() if q else None
        if next_song:
            await self._hook("on_song_start", chat_id, next_song)
          
