"""
Deals with commands and logic for hangman games.

*Classes*
---------
    Hangman()
        Deals with the game logic of hangman.
    DrawHangman()
        Draws the image shown to the player.
"""
import requests  # Used for getting the word in Hangman.start()
import datetime  # Used for generating the game id
import string  # string.ascii_uppercase used
import discord  # Used for discord.file and type hints
import math  # Used by DrawHangman(), mainly for drawing circles
import random  # Used to draw poorly

from discord_slash.context import SlashContext  # Used for typehints
from PIL import ImageDraw, Image, ImageFont  # Used to draw the image


class Hangman():
    """
    Controls hangman commands and game logic.

    *Methods*
    ---------
        start(ctx: SlashContext)
        stop(ctx: SlashContext)
        guess(message: discord.message, user: str, guess: str)
    """

    def __init__(self, bot):
        """
        Initialize the class.

        *Attributes*
        ------------
            draw: DrawHangman
                The DrawHangman used to draw the hangman image.
            APIURL: str
                The url to get the words from.
            APIPARAMS: dict
                The parameters to pass to every api call.
        """
        self.__bot = bot
        self.__draw = DrawHangman(bot)
        self.__APIURL = "https://api.wordnik.com/v4/words.json/randomWords?"
        apiKey = self.__bot.credentials["wordnik_key"]
        self.__APIPARAMS = {
            "hasDictionaryDef": True,
            "minCorpusCount": 5000,
            "maxCorpusCount": -1,
            "minDictionaryCount": 1,
            "maxDictionaryCount": -1,
            "minLength": 3,
            "maxLength": 11,
            "limit": 1,
            "api_key": apiKey
        }

    async def start(self, ctx: SlashContext):
        """
        Start a game of hangman.

        *Parameters*
        ------------
            ctx: SlashContext
                The context of the command.
        """
        await self.__bot.defer(ctx)
        channel = str(ctx.channel_id)
        user = f"#{ctx.author.id}"
        game = self.__bot.database["hangman games"].find_one({"_id": channel})
        user_name = self.__bot.database_funcs.get_name(user)
        startedGame = False

        if game is None:
            word = "-"
            while "-" in word or "." in word:
                response = requests.get(self.__APIURL, params=self.__APIPARAMS)
                word = list(response.json()[0]["word"].upper())

            self.__bot.log("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)

            self.__draw.drawImage(channel)

            log_message = "Game started"
            sendMessage = f"{user_name} started game of hangman."
            startedGame = True
        else:
            log_message = "There was already a game going on"
            sendMessage = self.__bot.long_strings["Hangman going on"]

        self.__bot.log(log_message)
        await ctx.send(sendMessage)

        if startedGame:
            boardsPath = "gwendolyn/resources/games/hangman_boards/"
            file_path = f"{boardsPath}hangman_board{channel}.png"
            newImage = await ctx.channel.send(file=discord.File(file_path))

            blankMessage = await ctx.channel.send("_ _")
            reactionMessages = {
                newImage: remainingLetters[:15],
                blankMessage: remainingLetters[15:]
            }

            old_messages = f"{newImage.id}\n{blankMessage.id}"

            with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "w") as f:
                f.write(old_messages)

            for message, letters in reactionMessages.items():
                for letter in letters:
                    emoji = chr(ord(letter)+127397)
                    await message.add_reaction(emoji)

    async def stop(self, ctx: SlashContext):
        """
        Stop the game of hangman.

        *Parameters*
        ------------
            ctx: SlashContext
                The context of the command.
        """
        channel = str(ctx.channel.id)
        game = self.__bot.database["hangman games"].find_one({"_id": channel})

        if game is None:
            await ctx.send("There's no game going on")
        elif f"#{ctx.author.id}" != game["player"]:
            await ctx.send("You can't end a game you're not in")
        else:
            self.__bot.database["hangman games"].delete_one({"_id": channel})

            with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f:
                messages = f.read().splitlines()

            for message in messages:
                old_message = await ctx.channel.fetch_message(int(message))
                self.__bot.log("Deleting old message")
                await old_message.delete()

            await ctx.send("Game stopped")

    async def guess(self, message: discord.Message, user: str, guess: str):
        """
        Guess a letter.

        *Parameters*
        ------------
            message: discord.Message
                The message that the reaction was placed on.
            user: str
                The id of the user.
            guess: str
                The guess.
        """
        channel = str(message.channel.id)
        hangman_games = self.__bot.database["hangman games"]
        game = hangman_games.find_one({"_id": channel})

        gameExists = (game is not None)
        singleLetter = (len(guess) == 1 and guess.isalpha())
        newGuess = (guess not in game["guessed letters"])
        validGuess = (gameExists and singleLetter and newGuess)

        if validGuess:
            self.__bot.log("Guessed the letter")
            correctGuess = 0

            for x, letter in enumerate(game["word"]):
                if guess == letter:
                    correctGuess += 1
                    updater = {"$set": {f"guessed.{x}": True}}
                    hangman_games.update_one({"_id": channel}, updater)

            if correctGuess == 0:
                updater = {"$inc": {"misses": 1}}
                hangman_games.update_one({"_id": channel}, updater)

            updater = {"$push": {"guessed letters": guess}}
            hangman_games.update_one({"_id": channel}, updater)

            remainingLetters = list(string.ascii_uppercase)

            game = hangman_games.find_one({"_id": channel})

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

            if correctGuess == 1:
                sendMessage = "Guessed {}. There was 1 {} in the word."
                sendMessage = sendMessage.format(guess, guess)
            else:
                sendMessage = "Guessed {}. There were {} {}s in the word."
                sendMessage = sendMessage.format(guess, correctGuess, guess)

            self.__draw.drawImage(channel)

            if game["misses"] == 6:
                hangman_games.delete_one({"_id": channel})
                sendMessage += self.__bot.long_strings["Hangman lost game"]
                remainingLetters = []
            elif all(game["guessed"]):
                hangman_games.delete_one({"_id": channel})
                self.__bot.money.addMoney(user, 15)
                sendMessage += self.__bot.long_strings["Hangman guessed word"]
                remainingLetters = []

            await message.channel.send(sendMessage)

            with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f:
                old_message_ids = f.read().splitlines()

            for oldID in old_message_ids:
                old_message = await message.channel.fetch_message(int(oldID))
                self.__bot.log("Deleting old message")
                await old_message.delete()

            boardsPath = "gwendolyn/resources/games/hangman_boards/"
            file_path = f"{boardsPath}hangman_board{channel}.png"
            newImage = await message.channel.send(file=discord.File(file_path))

            if len(remainingLetters) > 0:
                if len(remainingLetters) > 15:
                    blankMessage = await message.channel.send("_ _")
                    reactionMessages = {
                        newImage: remainingLetters[:15],
                        blankMessage: remainingLetters[15:]
                    }
                else:
                    blankMessage = ""
                    reactionMessages = {newImage: remainingLetters}

                if blankMessage != "":
                    old_messages = f"{newImage.id}\n{blankMessage.id}"
                else:
                    old_messages = str(newImage.id)

                old_imagePath = f"gwendolyn/resources/games/old_images/hangman{channel}"
                with open(old_imagePath, "w") as f:
                    f.write(old_messages)

                for message, letters in reactionMessages.items():
                    for letter in letters:
                        emoji = chr(ord(letter)+127397)
                        await message.add_reaction(emoji)


class DrawHangman():
    """
    Draws the image of the hangman game.

    *Methods*
    ---------
        drawImage(channel: str)
    """

    def __init__(self, bot):
        """
        Initialize the class.

        *Attributes*
        ------------
            CIRCLESIZE
            LINEWIDTH
            BODYSIZE
            LIMBSIZE
            ARMPOSITION
            MANX, MANY
            LETTERLINELENGTH
            LETTERLINEDISTANCE
            GALLOWX, GALLOWY
            PHI
            FONT
            SMALLFONT
        """
        self.__bot = bot
        self.__CIRCLESIZE = 120
        self.__LINEWIDTH = 12

        self.__BODYSIZE = 210
        self.__LIMBSIZE = 60
        self.__ARMPOSITION = 60

        self.__MANX = (self.__LIMBSIZE*2)
        self.__MANY = (self.__CIRCLESIZE+self.__BODYSIZE+self.__LIMBSIZE)
        MANPADDING = self.__LINEWIDTH*4
        self.__MANX += MANPADDING
        self.__MANY += MANPADDING

        self.__LETTERLINELENGTH = 90
        self.__LETTERLINEDISTANCE = 30

        self.__GALLOWX, self.__GALLOWY = 360, 600
        self.__PHI = 1-(1 / ((1 + 5 ** 0.5) / 2))

        LETTERSIZE = 75  # Wrong guesses letter size
        WORDSIZE = 70  # Correct guesses letter size

        FONTPATH = "gwendolyn/resources/fonts/comic-sans-bold.ttf"
        self.__FONT = ImageFont.truetype(FONTPATH, LETTERSIZE)
        self.__SMALLFONT = ImageFont.truetype(FONTPATH, WORDSIZE)

    def __deviate(self, preDeviance: int, preDevianceAccuracy: int,
                  positionChange: float, maxmin: int,
                  maxAcceleration: float):
        randomDeviance = random.uniform(-positionChange, positionChange)
        devianceAccuracy = preDevianceAccuracy + randomDeviance
        if devianceAccuracy > maxmin * maxAcceleration:
            devianceAccuracy = maxmin * maxAcceleration
        elif devianceAccuracy < -maxmin * maxAcceleration:
            devianceAccuracy = -maxmin * maxAcceleration

        deviance = preDeviance + devianceAccuracy
        if deviance > maxmin:
            deviance = maxmin
        elif deviance < -maxmin:
            deviance = -maxmin
        return deviance, devianceAccuracy

    def __badCircle(self):
        circlePadding = (self.__LINEWIDTH*3)
        imageWidth = self.__CIRCLESIZE+circlePadding
        imageSize = (imageWidth, imageWidth)
        background = Image.new("RGBA", imageSize, color=(0, 0, 0, 0))

        d = ImageDraw.Draw(background, "RGBA")
        middle = (self.__CIRCLESIZE+(self.__LINEWIDTH*3))/2
        devianceX = 0
        devianceY = 0
        devianceAccuracyX = 0
        devianceAccuracyY = 0
        start = random.randint(-100, -80)
        degreesAmount = 360 + random.randint(-10, 30)

        for degree in range(degreesAmount):
            devianceXParams = [
                devianceX,
                devianceAccuracyX,
                self.__LINEWIDTH/100,
                self.__LINEWIDTH,
                0.03
            ]
            devianceYParams = [
                devianceY,
                devianceAccuracyY,
                self.__LINEWIDTH/100,
                self.__LINEWIDTH,
                0.03
            ]
            devianceX, devianceAccuracyX = self.__deviate(*devianceXParams)
            devianceY, devianceAccuracyY = self.__deviate(*devianceYParams)

            radians = math.radians(degree+start)
            circleX = (math.cos(radians) * (self.__CIRCLESIZE/2))
            circleY = (math.sin(radians) * (self.__CIRCLESIZE/2))

            x = middle + circleX - (self.__LINEWIDTH/2) + devianceX
            y = middle + circleY - (self.__LINEWIDTH/2) + devianceY

            circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
            d.ellipse(circlePosition, fill=(0, 0, 0, 255))

        return background

    def __badLine(self, length: int, rotated: bool = False):
        if rotated:
            w, h = length+self.__LINEWIDTH*3, self.__LINEWIDTH*3
        else:
            w, h = self.__LINEWIDTH*3, length+self.__LINEWIDTH*3
        background = Image.new("RGBA", (w, h), color=(0, 0, 0, 0))

        d = ImageDraw.Draw(background, "RGBA")

        possibleDeviance = int(self.__LINEWIDTH/3)
        devianceX = random.randint(-possibleDeviance, possibleDeviance)
        devianceY = 0
        devianceAccuracyX = 0
        devianceAccuracyY = 0

        for pixel in range(length):
            devianceParamsX = [
                devianceX,
                devianceAccuracyX,
                self.__LINEWIDTH/1000,
                self.__LINEWIDTH,
                0.004
            ]
            devianceParamsY = [
                devianceY,
                devianceAccuracyY,
                self.__LINEWIDTH/1000,
                self.__LINEWIDTH,
                0.004
            ]
            devianceX, devianceAccuracyX = self.__deviate(*devianceParamsX)
            devianceY, devianceAccuracyY = self.__deviate(*devianceParamsY)

            if rotated:
                x = self.__LINEWIDTH + pixel + devianceX
                y = self.__LINEWIDTH + devianceY
            else:
                x = self.__LINEWIDTH + devianceX
                y = self.__LINEWIDTH + pixel + devianceY

            circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
            d.ellipse(circlePosition, fill=(0, 0, 0, 255))

        return background

    def __drawMan(self, misses: int, seed: str):
        random.seed(seed)
        manSize = (self.__MANX, self.__MANY)
        background = Image.new("RGBA", manSize, color=(0, 0, 0, 0))

        if misses >= 1:
            head = self.__badCircle()
            pasteX = (self.__MANX-(self.__CIRCLESIZE+(self.__LINEWIDTH*3)))//2
            pastePosition = (pasteX, 0)
            background.paste(head, pastePosition, head)
        if misses >= 2:
            body = self.__badLine(self.__BODYSIZE)
            pasteX = (self.__MANX-(self.__LINEWIDTH*3))//2
            pastePosition = (pasteX, self.__CIRCLESIZE)
            background.paste(body, pastePosition, body)

        if misses >= 3:
            limbs = random.sample(["rl", "ll", "ra", "la"], min(misses-2, 4))
        else:
            limbs = []

        random.seed(seed)

        for limb in limbs:
            limbDrawing = self.__badLine(self.__LIMBSIZE, True)
            xPosition = (self.__MANX-(self.__LINEWIDTH*3))//2

            if limb[1] == "a":
                rotation = random.randint(-45, 45)
                shift = math.sin(math.radians(rotation))
                lineLength = self.__LIMBSIZE+(self.__LINEWIDTH*3)
                compensation = int(shift*lineLength)
                limbDrawing = limbDrawing.rotate(rotation, expand=1)
                yPosition = self.__CIRCLESIZE + self.__ARMPOSITION
                if limb == "ra":
                    compensation = min(-compensation, 0)
                else:
                    xPosition -= self.__LIMBSIZE
                    compensation = min(compensation, 0)

                yPosition += compensation
            else:
                rotation = random.randint(-15, 15)
                yPosition = self.__CIRCLESIZE+self.__BODYSIZE-self.__LINEWIDTH
                if limb == "rl":
                    limbDrawing = limbDrawing.rotate(rotation-45, expand=1)
                else:
                    xPosition += -limbDrawing.size[0]+self.__LINEWIDTH*3
                    limbDrawing = limbDrawing.rotate(rotation+45, expand=1)

            pastePosition = (xPosition, yPosition)
            background.paste(limbDrawing, pastePosition, limbDrawing)

        return background

    def __badText(self, text: str, big: bool, color: tuple = (0, 0, 0, 255)):
        if big:
            font = self.__FONT
        else:
            font = self.__SMALLFONT
        w, h = font.getsize(text)
        img = Image.new("RGBA", (w, h), color=(0, 0, 0, 0))
        d = ImageDraw.Draw(img, "RGBA")

        d.text((0, 0), text, font=font, fill=color)
        return img

    def __drawGallows(self):
        gallowSize = (self.__GALLOWX, self.__GALLOWY)
        background = Image.new("RGBA", gallowSize, color=(0, 0, 0, 0))

        bottomLine = self.__badLine(int(self.__GALLOWX * 0.75), True)
        bottomLineX = int(self.__GALLOWX * 0.125)
        bottomLineY = self.__GALLOWY-(self.__LINEWIDTH*4)
        pastePosition = (bottomLineX, bottomLineY)
        background.paste(bottomLine, pastePosition, bottomLine)

        lineTwo = self.__badLine(self.__GALLOWY-self.__LINEWIDTH*6)
        lineTwoX = int(self.__GALLOWX*(0.75*self.__PHI))
        lineTwoY = self.__LINEWIDTH*2
        pastePosition = (lineTwoX, lineTwoY)
        background.paste(lineTwo, pastePosition, lineTwo)

        topLine = self.__badLine(int(self.__GALLOWY*0.30), True)
        pasteX = int(self.__GALLOWX*(0.75*self.__PHI))-self.__LINEWIDTH
        pastePosition = (pasteX, self.__LINEWIDTH*3)
        background.paste(topLine, pastePosition, topLine)

        lastLine = self.__badLine(int(self.__GALLOWY*0.125))
        pasteX += int(self.__GALLOWY*0.30)
        background.paste(lastLine, (pasteX, self.__LINEWIDTH*3), lastLine)
        return background

    def __drawLetterLines(self, word: str, guessed: list, misses: int):
        letterWidth = self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE
        imageWidth = letterWidth*len(word)
        imageSize = (imageWidth, self.__LETTERLINELENGTH+self.__LINEWIDTH*3)
        letterLines = Image.new("RGBA", imageSize, color=(0, 0, 0, 0))
        for x, letter in enumerate(word):
            line = self.__badLine(self.__LETTERLINELENGTH, True)
            pasteX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
            pastePosition = (pasteX, self.__LETTERLINELENGTH)
            letterLines.paste(line, pastePosition, line)
            if guessed[x]:
                letterDrawing = self.__badText(letter, True)
                letterWidth = self.__FONT.getsize(letter)[0]
                letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
                letterX -= (letterWidth//2)
                letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
                letterLines.paste(letterDrawing, (letterX, 0), letterDrawing)
            elif misses == 6:
                letterDrawing = self.__badText(letter, True, (242, 66, 54))
                letterWidth = self.__FONT.getsize(letter)[0]
                letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
                letterX -= (letterWidth//2)
                letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
                letterLines.paste(letterDrawing, (letterX, 0), letterDrawing)

        return letterLines

    def __shortestDist(self, positions: list, newPosition: tuple):
        __shortestDist = math.inf
        x, y = newPosition
        for i, j in positions:
            xDistance = abs(i-x)
            yDistance = abs(j-y)
            dist = math.sqrt(xDistance**2+yDistance**2)
            if __shortestDist > dist:
                __shortestDist = dist
        return __shortestDist

    def __drawMisses(self, guesses: list, word: str):
        background = Image.new("RGBA", (600, 400), color=(0, 0, 0, 0))
        pos = []
        for guess in guesses:
            if guess not in word:
                placed = False
                while not placed:
                    letter = self.__badText(guess, True)
                    w, h = self.__FONT.getsize(guess)
                    x = random.randint(0, 600-w)
                    y = random.randint(0, 400-h)
                    if self.__shortestDist(pos, (x, y)) > 70:
                        pos.append((x, y))
                        background.paste(letter, (x, y), letter)
                        placed = True
        return background

    def drawImage(self, channel: str):
        """
        Draw a hangman Image.

        *Parameters*
        ------------
            channel: str
                The id of the channel the game is in.
        """
        self.__bot.log("Drawing hangman image", channel)
        game = self.__bot.database["hangman games"].find_one({"_id": channel})

        random.seed(game["game ID"])

        background = Image.open("gwendolyn/resources/paper.jpg")
        gallow = self.__drawGallows()
        man = self.__drawMan(game["misses"], game["game ID"])

        random.seed(game["game ID"])
        letterLineParams = [game["word"], game["guessed"], game["misses"]]
        letterLines = self.__drawLetterLines(*letterLineParams)

        random.seed(game["game ID"])
        misses = self.__drawMisses(game["guessed letters"], game["word"])

        background.paste(gallow, (100, 100), gallow)
        background.paste(man, (300, 210), man)
        background.paste(letterLines, (120, 840), letterLines)
        background.paste(misses, (600, 150), misses)

        missesText = self.__badText("MISSES", False)
        missesTextWidth = missesText.size[0]
        background.paste(missesText, (850-missesTextWidth//2, 50), missesText)

        boardPath = f"gwendolyn/resources/games/hangman_boards/hangman_board{channel}.png"
        background.save(boardPath)
