import random
import copy
import math

from .fourInARowDraw import DrawFourInARow
from funcs import logThis

AIScores = {
    "middle": 3,
    "two in a row": 10,
    "three in a row": 50,
    "enemy two in a row": -35,
    "enemy three in a row": -200,
    "enemy win": -10000,
    "win": 10000,
    "avoid losing": 100
}

rowCount = 6
columnCount = 7
easy = True

class FourInARow():
    def __init__(self,bot):
        self.bot = bot
        self.draw = DrawFourInARow(bot)

    # Starts the game
    def fourInARowStart(self, channel, user, opponent):
        game = self.bot.database["4 in a row games"].find_one({"_id":channel})

        if game == None:

            if opponent in ["1","2","3","4","5"]:
                difficulty = int(opponent)
                diffText = " with difficulty "+opponent
                opponent = "Gwendolyn"
            elif opponent.lower() == "gwendolyn":
                difficulty = 3
                diffText = " with difficulty 3"
                opponent = "Gwendolyn"
            else:
                try:
                    int(opponent)
                    return "That difficulty doesn't exist", False, False, False, False
                except:
                    # Opponent is another player
                    opponent = self.bot.funcs.getID(opponent)
                    if opponent != None:
                        difficulty = 5
                        diffText = ""
                    else:
                        return "I can't find that user", False, False, False, False

                    if user == opponent:
                        return "You can't play against yourself", False, False, False, False

            board = [ [ 0 for i in range(columnCount) ] for j in range(rowCount) ]
            players = [user,opponent]
            random.shuffle(players)

            newGame = {"_id":channel,"board": board,"winner":0,"win direction":"",
                "win coordinates":[0,0],"players":players,"turn":0,"difficulty":difficulty}

            self.bot.database["4 in a row games"].insert_one(newGame)

            self.draw.drawImage(channel)

            gwendoTurn = False

            if players[0] == "Gwendolyn":
                gwendoTurn = True

            return "Started game against "+self.bot.funcs.getName(opponent)+diffText+". It's "+self.bot.funcs.getName(players[0])+"'s turn", True, False, False, gwendoTurn
        else:
            return "There's already a 4 in a row game going on in this channel", False, False, False, False

    # Places a piece at the lowest available point in a specific column
    def placePiece(self, channel : str,player : int,column : int):
        game = self.bot.database["4 in a row games"].find_one({"_id":channel})

        if game != None:
            board = game["board"]

            board = self.placeOnBoard(board,player,column)

            if board != None:
                self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"board":board}})
                turn = (game["turn"]+1)%2
                self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"turn":turn}})

                logThis("Checking for win")
                won, winDirection, winCoordinates = self.isWon(board)

                if won != 0:
                    gameWon = True
                    self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"winner":won}})
                    self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"win direction":winDirection}})
                    self.bot.database["4 in a row games"].update_one({"_id":channel},
                        {"$set":{"win coordinates":winCoordinates}})

                    message = self.bot.funcs.getName(game["players"][won-1])+" placed a piece in column "+str(column+1)+" and won."
                    winAmount = int(game["difficulty"])**2+5
                    if game["players"][won-1] != "Gwendolyn":
                        message += " Adding "+str(winAmount)+" GwendoBucks to their account."
                elif 0 not in board[0]:
                    gameWon = True
                    message = "It's a draw!"
                else:
                    gameWon = False
                    message = self.bot.funcs.getName(game["players"][player-1])+" placed a piece in column "+str(column+1)+". It's now "+self.bot.funcs.getName(game["players"][turn])+"'s turn."

                gwendoTurn = False

                if game["players"][turn] == "Gwendolyn":
                    logThis("It's Gwendolyn's turn")
                    gwendoTurn = True

                self.draw.drawImage(channel)
                return message, True, True, gameWon, gwendoTurn
            else:
                return "There isn't any room in that column", True, True, False, False
        else:
            return "There's no game in this channel", False, False, False, False

    # Returns a board where a piece has been placed in the column
    def placeOnBoard(self,board,player,column):
        placementx, placementy = -1, column

        for x, line in enumerate(board):
            if line[column] == 0:
                placementx = x

        board[placementx][placementy] = player

        if placementx == -1:
            return None
        else:
            return board

    # Parses command
    def parseFourInARow(self, command, channel, user):
        commands = command.split()
        if command == "" or command == " ":
            return "I didn't get that. Use \"!fourinarow start [opponent]\" to start a game. To play against the computer, use difficulty 1 through 5 as the [opponent].", False, False, False, False
        elif commands[0] == "start":
            # Starting a game
            if len(commands) == 1: # if the commands is "!fourinarow start", the opponent is Gwendolyn
                commands.append("3")
            return self.fourInARowStart(channel,user,commands[1]) # commands[1] is the opponent

        # Stopping the game
        elif commands[0] == "stop":
            game = self.bot.database["4 in a row games"].find_one({"_id":channel})

            if user in game["players"]:
                return "Ending game.", False, False, True, False
            else:
                return "You can't end a game where you're not a player.", False, False, False, False

        # Placing manually
        elif commands[0] == "place":
            try:
                return self.placePiece(channel,int(commands[1]),int(commands[2])-1)
            except:
                return "I didn't get that. To place a piece use \"!fourinarow place [player number] [column]\" or press the corresponding message-reaction beneath the board.", False, False, False, False
        else:
            return "I didn't get that. Use \"!fourinarow start [opponent]\" to start a game. To play against the computer, use difficulty 1 through 5 as the [opponent].", False, False, False, False

    # Checks if someone has won the game and returns the winner
    def isWon(self, board):
        won = 0
        winDirection = ""
        winCoordinates = [0,0]

        for row in range(rowCount):
            for place in range(columnCount):
                if won == 0:
                    piecePlayer = board[row][place]
                    if piecePlayer != 0:
                        # Checks horizontal
                        if place <= columnCount-4:
                            pieces = [board[row][place+1],board[row][place+2],board[row][place+3]]
                        else:
                            pieces = [0]

                        if all(x == piecePlayer for x in pieces):
                            won = piecePlayer
                            winDirection = "h"
                            winCoordinates = [row,place]

                        # Checks vertical
                        if row <= rowCount-4:
                            pieces = [board[row+1][place],board[row+2][place],board[row+3][place]]
                        else:
                            pieces = [0]

                        if all(x == piecePlayer for x in pieces):
                            won = piecePlayer
                            winDirection = "v"
                            winCoordinates = [row,place]

                        # Checks right diagonal
                        if row <= rowCount-4 and place <= columnCount-4:
                            pieces = [board[row+1][place+1],board[row+2][place+2],board[row+3][place+3]]
                        else:
                            pieces = [0]

                        if all(x == piecePlayer for x in pieces):
                            won = piecePlayer
                            winDirection = "r"
                            winCoordinates = [row,place]

                        # Checks left diagonal
                        if row <= rowCount-4 and place >= 3:
                            pieces = [board[row+1][place-1],board[row+2][place-2],board[row+3][place-3]]
                        else:
                            pieces = [0]

                        if all(x == piecePlayer for x in pieces):
                            won = piecePlayer
                            winDirection = "l"
                            winCoordinates = [row,place]


        return won, winDirection, winCoordinates

    # Plays as the AI
    async def fourInARowAI(self, channel):
        logThis("Figuring out best move")
        game = self.bot.database["4 in a row games"].find_one({"_id":channel})

        board = game["board"]
        player = game["players"].index("Gwendolyn")+1
        difficulty = game["difficulty"]

        scores = [-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf]
        for column in range(0,columnCount):
            testBoard = copy.deepcopy(board)
            testBoard = self.placeOnBoard(testBoard,player,column)
            if testBoard != None:
                scores[column] = await self.minimax(testBoard,difficulty,player%2+1,player,-math.inf,math.inf,False)
            logThis("Best score for column "+str(column)+" is "+str(scores[column]))

        possibleScores = scores.copy()

        while (min(possibleScores) <= (max(possibleScores) - max(possibleScores)/10)) and len(possibleScores) != 1:
            possibleScores.remove(min(possibleScores))

        highest_score = random.choice(possibleScores)

        indices = [i for i, x in enumerate(scores) if x == highest_score]
        placement = random.choice(indices)
        return self.placePiece(channel,player,placement)

    # Calculates points for a board
    def AICalcPoints(self,board,player):
        score = 0
        otherPlayer = player%2+1

        # Adds points for middle placement
        # Checks horizontal
        for row in range(rowCount):
            if board[row][3] == player:
                score += AIScores["middle"]
            rowArray = [int(i) for i in list(board[row])]
            for place in range(columnCount-3):
                window = rowArray[place:place+4]
                score += self.evaluateWindow(window,player,otherPlayer)

        # Checks Vertical
        for column in range(columnCount):
            columnArray = [int(i[column]) for i in list(board)]
            for place in range(rowCount-3):
                window = columnArray[place:place+4]
                score += self.evaluateWindow(window,player,otherPlayer)

        # Checks right diagonal
        for row in range(rowCount-3):
            for place in range(columnCount-3):
                window = [board[row][place],board[row+1][place+1],board[row+2][place+2],board[row+3][place+3]]
                score += self.evaluateWindow(window,player,otherPlayer)

            for place in range(3,columnCount):
                window = [board[row][place],board[row+1][place-1],board[row+2][place-2],board[row+3][place-3]]
                score += self.evaluateWindow(window,player,otherPlayer)


        ## Checks if anyone has won
        #won = isWon(board)[0]

        ## Add points if AI wins
        #if won == player:
        #    score += AIScores["win"]

        return score


    def evaluateWindow(self, window,player,otherPlayer):
        if window.count(player) == 4:
            return AIScores["win"]
        elif window.count(player) == 3 and window.count(0) == 1:
            return AIScores["three in a row"]
        elif window.count(player) == 2 and window.count(0) == 2:
            return AIScores["two in a row"]
        elif window.count(otherPlayer) == 4:
            return AIScores["enemy win"]
        else:
            return 0

    async def minimax(self, board, depth, player , originalPlayer, alpha, beta, maximizingPlayer):
        #terminal = ((0 not in board[0]) or (isWon(board)[0] != 0))
        terminal = 0 not in board[0]
        points = self.AICalcPoints(board,originalPlayer)
        # The depth is how many moves ahead the computer checks. This value is the difficulty.
        if depth == 0 or terminal or (points > 5000 or points < -6000):
            return points
        if maximizingPlayer:
            value = -math.inf
            for column in range(0,columnCount):
                testBoard = copy.deepcopy(board)
                testBoard = self.placeOnBoard(testBoard,player,column)
                if testBoard != None:
                    evaluation = await self.minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,False)
                    if evaluation < -9000: evaluation += AIScores["avoid losing"]
                    value = max(value,evaluation)
                    alpha = max(alpha,evaluation)
                    if beta <= alpha: break
            return value
        else:
            value = math.inf
            for column in range(0,columnCount):
                testBoard = copy.deepcopy(board)
                testBoard = self.placeOnBoard(testBoard,player,column)
                if testBoard != None:
                    evaluation = await self.minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,True)
                    if evaluation < -9000: evaluation += AIScores["avoid losing"]
                    value = min(value,evaluation)
                    beta = min(beta,evaluation)
                    if beta <= alpha: break
            return value
