import asyncio
from channels.generic.websocket import AsyncWebsocketConsumer
from .backend.game import Game
from channels.db import database_sync_to_async


class TimerConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()
        self.gameid = self.scope["url_route"]["kwargs"]["gameid"]
        self.game = await self.getGame()
        timer = await self.getRemainingTimer()
        await self.send(text_data=str(timer))
        self.timerTask = asyncio.ensure_future(self.timer(timer))

    async def timer(self, timer):
        await asyncio.sleep(1)
        try:
            while timer >= 0:
                if self.game.running:
                    await self.send(text_data=str(timer))
                    timer -= 1
                    await asyncio.sleep(1)
                else:
                    await self.send(text_data="game not started")
                    self.game = await self.getGame()
                    await asyncio.sleep(1)
        except asyncio.CancelledError:
            pass
        finally:
            self.game = await self.getGame()
            if self.game.currentRound > self.game.maxRounds:
                await self.send(text_data="endGame")
            else:
                await self.send(text_data="nextRound")

    @database_sync_to_async
    def getRemainingTimer(self):
        return self.game.timer.remainingtimer

    @database_sync_to_async
    def getGame(self):
        return Game.objects.get(id=self.gameid)

    @database_sync_to_async
    def processGameround(self, game):
        gameend = game.processGameround()

    async def receive(self, event):
        pass

    async def disconnect(self, event):
        self.timerTask.cancel()
