import time
from AbhiCalls.queue import SongQueue

class Player:
    def __init__(self, engine):
        self.engine = engine
        self.queues = {}
        self.start_time = {}

    def _queue(self, chat_id):
        return self.queues.setdefault(chat_id, SongQueue())

    async def play(self, chat_id, song):
        q = self._queue(chat_id)
        pos = q.add(song)

        if pos == 1:
            self.start_time[chat_id] = time.time()
            await self.engine.play(chat_id, song.stream)

        return pos

    async def skip(self, chat_id):
        q = self.queues.get(chat_id)
        if not q:
            return
        nxt = q.next()
        if nxt:
            self.start_time[chat_id] = time.time()
            await self.engine.play(chat_id, nxt.stream)
        else:
            await self.engine.stop(chat_id)

    async def previous(self, chat_id):
        q = self.queues.get(chat_id)
        if not q:
            return None
        prev = q.previous()
        if prev:
            self.start_time[chat_id] = time.time()
            await self.engine.play(chat_id, prev.stream)
        return prev

    async def stop(self, chat_id):
        if chat_id in self.queues:
            self.queues[chat_id].clear()
        await self.engine.stop(chat_id)

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

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

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

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

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

    def set_loop(self, chat_id, count=None):
        q = self._queue(chat_id)
        if count is None:
            q.infinite_loop = not q.infinite_loop
            return q.infinite_loop

        cur = q.current()
        if cur:
            cur.loop_left = count - 1
            return count
        return 0

    def eta(self, chat_id):
        q = self.queues.get(chat_id)
        if not q or not q.current():
            return None
        elapsed = int(time.time() - self.start_time.get(chat_id, 0))
        return max(q.current().duration_sec - elapsed, 0)
      
