import json

from . import draw4InARow

# Starts the game
def fourInARowStart(channel):
    with open("resources/games/games.json", "r") as f:
        data = json.load(f)
    
    if channel not in data["4 in a row games"]:

        board = [ [ 0 for i in range(7) ] for j in range(6) ]

        data["4 in a row games"][channel] = {"board": board}

        with open("resources/games/games.json", "w") as f:
            json.dump(data,f,indent=4)
        
        draw4InARow.drawImage(channel)

        return "Started game", True
    else:
        return "There's already a 4 in a row game going on in this channel", False

# Places a piece at the lowest available point in a specific column
def placePiece(channel : str,player : int,column : int):
    with open("resources/games/games.json", "r") as f:
        data = json.load(f)
    
    if channel in data["4 in a row games"]:
        board = data["4 in a row games"][channel]["board"]

        placementx, placementy = -1, column

        for x in range(len(board)):
            if board[x][column] == 0:
                placementx = x
        
        
        if placementx != -1:
            board[placementx][placementy] = player
            data["4 in a row games"][channel]["board"] = board

            with open("resources/games/games.json", "w") as f:
                json.dump(data,f,indent=4)
            
            draw4InARow.drawImage(channel)
            return "Placed the piece", True
        else:
            return "There isn't any room in that column", True
    else:
        return "There's no game in this channel", False
    

# Parses command
def parseFourInARow(command, channel, user):
    if command == "" or command == " ":
        return fourInARowStart(channel)
    elif command.startswith(" place"):
        commands = command.split(" ")
        try:
            return placePiece(channel,int(commands[2]),int(commands[3])-1)
        except:
            return "I didn't quite get that", False
    else:
        return "I didn't get that", False