from ..AGame import AGame

from channels.generic.websocket import WebsocketConsumer

from .TicTacToePlayer import TicTacToePlayer

from .TicTacToeSpectator import TicTacToeSpectator

import time

class TicTacToeGame(AGame):
    
    
    def __init__(self, game_id: int, game_manager):
        super().__init__("tictactoe", game_id, game_manager)

        players_id: list[int] = self.model.get_players_id()

        self.players: list[TicTacToePlayer] = [TicTacToePlayer(player_id, None, self, ["x", "o"][i]) for i, player_id in enumerate(players_id)]

        self._map = [[-1 for _ in range(9)] for _ in range(9)]
        
    def _everbody_is_here(self):
        return len(self.players) == len(self.get_players_connected())

    def _player_join(self, user_id: int, socket: WebsocketConsumer):
        
        player = self.get_player_by_user_id(user_id)
        if (player is None):
            return None
        
        # check if player is already connected
        if (player.is_connected()):
            player.disconnect(1001)

        player.socket = socket
        return player

    def add(self, newmove, player):
        for i in self._map:
            print(i)

        print(newmove.get("targetMorpion"), newmove.get("targetCase"), newmove.get("sign"))

        if (self.checkMove(newmove, player)):
            self._map[newmove.get("targetMorpion")][newmove.get("targetCase")] = newmove.get("sign")
            player.currentMorpion = int(newmove.get("targetMorpion"))
            return True

        return False

    def checkMove(self, newmove, player):
        print(int(newmove.get("targetMorpion")), player.currentMorpion)
        if (int(newmove.get("targetMorpion")) != player.currentMorpion):
            return False
        
        if (self._map[newmove.get("targetMorpion")][newmove.get("targetCase")] != -1):
            return False
        
        return True

    def checkWin(self):
        for tab in self._map:
            for i in range(3):
                if tab[i] == tab[i + 3] == tab[i + 6]:
                    return tab[i]
            for i in range(0, 9, 3):
                if tab[i] == tab[i + 1] == tab[i + 2]:
                    return tab[i]
            if tab[0] == tab[4] == tab[8]:
                return tab[0]
            if tab[6] == tab[4] == tab[2]:
                return tab[6]
        return None

        
    def _spectator_join(self, user_id: int, socket: WebsocketConsumer):
        
        spectator:TicTacToeSpectator = TicTacToeSpectator(user_id, socket, self)
        
        self.spectators.append(spectator)
        
        return spectator    
    
    def join(self, user_id: int, socket: WebsocketConsumer) -> TicTacToeSpectator | TicTacToePlayer:
        member: TicTacToePlayer = self._player_join(user_id, socket)

        if (member is None):
            member: TicTacToeSpectator = self._spectator_join(user_id, socket)

        return member  