import json, urllib, datetime, string

from . import hangmanDraw, money
from funcs import getName, logThis

apiUrl = "https://api.wordnik.com/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=5000&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=3&maxLength=11&limit=1&api_key="

def hangmanStart(channel,user,apiKey):
    with open("resources/games/hangmanGames.json", "r") as f:
        data = json.load(f)

    if channel not in data:
        with urllib.request.urlopen(apiUrl+apiKey) as p:
            word = list(json.load(p)[0]["word"].upper())
        logThis("Found the word \""+"".join(word)+"\"")
        guessed = [False] * len(word)
        gameID = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        data[channel] = {"player" : user,"guessed letters" : [],"word" : word,"game ID" : gameID,"misses" : 0,"guessed" : guessed}

        remainingLetters = list(string.ascii_uppercase)

        with open("resources/games/hangmanGames.json", "w") as f:
            json.dump(data,f)

        try:
            hangmanDraw.drawImage(channel)
        except:
            logThis("Error drawing image (error code 1710)")
        return f"{getName(user)} started game of hangman.", True, False, remainingLetters
    else:
        return "There's already a Hangman game going on in the channel", False, False, []

def hangmanStop(channel):
    with open("resources/games/hangmanGames.json", "r") as f:
        data = json.load(f)

    del data[channel]
    with open("resources/games/hangmanGames.json", "w") as f:
        json.dump(data,f,indent=4)

    return "Game stopped.", False, False, []

def hangmanGuess(channel,user,guess):
    with open("resources/games/hangmanGames.json", "r") as f:
        data = json.load(f)

    if channel in data:
        if user == data[channel]["player"]:
            if len(guess) == 1:
                if guess not in data[channel]["guessed letters"]:
                    correctGuess = 0

                    for x, letter in enumerate(data[channel]["word"]):
                        if guess == letter:
                            correctGuess += 1
                            data[channel]["guessed"][x] = True

                    if correctGuess == 0:
                        data[channel]["misses"] += 1

                    data[channel]["guessed letters"].append(guess)

                    remainingLetters = list(string.ascii_uppercase)

                    for letter in data[channel]["guessed letters"]:
                        remainingLetters.remove(letter)

                    if correctGuess == 1:
                        message = f"Guessed {guess}. There was 1 {guess} in the word."
                    else:
                        message = f"Guessed {guess}. There were {correctGuess} {guess}s in the word."

                    with open("resources/games/hangmanGames.json", "w") as f:
                        json.dump(data,f)

                    try:
                        hangmanDraw.drawImage(channel)
                    except:
                        logThis("Error drawing image (error code 1710)")

                    if data[channel]["misses"] == 6:
                        hangmanStop(channel)
                        return message+" You've guessed wrong six times and have lost the game.", True, True, []
                    elif all(i == True for i in data[channel]["guessed"]):
                        hangmanStop(channel)
                        money.addMoney(user,15)
                        return message+" You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account", True, True, []
                    else:
                        return message, True, True, remainingLetters
                else:
                    return f"You've already guessed {guess}", False, False, []
            else:
                return "", False, False, []
        else:
            return "", False, False, []
    else:
        return "There's no Hangman game going on in this channel", False, False, []

def parseHangman(channel,user,command,apiKey):
    if command == "start":
        try:
            return hangmanStart(channel,user,apiKey)
        except:
            logThis("Error starting game (error code 1730)")
    elif command == "stop":
        return hangmanStop(channel)
    elif command.startswith("guess "):
        guess = command[6:].upper()
        try:
            return hangmanGuess(channel,user,guess)
        except:
            logThis("Error in guessing (Error Code 1720)")
    else:
        return "I didn't understand that", False, False, []
