import json, urllib, datetime, string

from .hangmanDraw import DrawHangman
from funcs import 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="

class Hangman():
    def __init__(self,bot):
        self.bot = bot
        self.draw = DrawHangman(bot)

    def hangmanStart(self,channel,user):
        game = self.bot.database["hangman games"].find_one({"_id":channel})

        if game == None:
            apiKey = self.bot.credentials.wordnikKey
            word = "-"
            while "-" in word or "." in word:
                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')
            newGame = {"_id":channel,"player" : user,"guessed letters" : [],"word" : word,"game ID" : gameID,"misses" : 0,"guessed" : guessed}
            self.bot.database["hangman games"].insert_one(newGame)

            remainingLetters = list(string.ascii_uppercase)

            try:
                self.draw.drawImage(channel)
            except:
                logThis("Error drawing image (error code 1710)")
            return f"{self.bot.funcs.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(self,channel):
        self.bot.database["hangman games"].delete_one({"_id":channel})

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

    def hangmanGuess(self,channel,user,guess):
        game = self.bot.database["hangman games"].find_one({"_id":channel})

        if game != None:
            if user == game["player"]:
                if len(guess) == 1 and guess in list(string.ascii_uppercase):
                    if guess not in game["guessed letters"]:
                        correctGuess = 0

                        for x, letter in enumerate(game["word"]):
                            if guess == letter:
                                correctGuess += 1
                                self.bot.database["hangman games"].update_one({"_id":channel},{"$set":{"guessed."+str(x):True}})

                        if correctGuess == 0:
                            self.bot.database["hangman games"].update_one({"_id":channel},{"$inc":{"misses":1}})

                        self.bot.database["hangman games"].update_one({"_id":channel},{"$push":{"guessed letters":guess}})

                        remainingLetters = list(string.ascii_uppercase)

                        game = self.bot.database["hangman games"].find_one({"_id":channel})

                        for letter in game["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."

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

                        if game["misses"] == 6:
                            self.hangmanStop(channel)
                            return message+" You've guessed wrong six times and have lost the game.", True, True, []
                        elif all(i == True for i in game["guessed"]):
                            self.hangmanStop(channel)
                            self.bot.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(self,channel,user,command):
        if command == "start":
            try:
                return self.hangmanStart(channel,user)
            except:
                logThis("Error starting game (error code 1730)")
        elif command == "stop":
            return self.hangmanStop(channel)
        elif command.startswith("guess "):
            guess = command[6:].upper()
            try:
                return self.hangmanGuess(channel,user,guess)
            except:
                logThis("Error in guessing (Error Code 1720)")
        else:
            return "I didn't understand that", False, False, []
