import math

from funcs import logThis

from PIL import Image, ImageDraw

w, h = 1440, 1440
largeSpace = 190
smallSpace = math.floor((w - 2*largeSpace)/9)
avatarSize = 50
avatarHalf = math.floor(avatarSize/2)
avatarBuffer = 10

class DrawMonopoly():
    def __init__(self,bot):
        self.bot = bot

    def drawImage(self, channel):
        logThis("Drawing monopoly board for "+channel)
        game = self.bot.database["monopoly games"].find_one({"_id":channel})

        board = Image.open("resources/games/monopolyBoard.png")
        d = ImageDraw.Draw(board,"RGBA")
        places = {}

        for key, value in list(game["players"].items()):
            logThis("Drawing "+key)
            if value["position"] in places:
                places[value["position"]].append(key)
            else:
                places[value["position"]] = [key]

        for key, value in list(places.items()):
            for number, player in enumerate(value):
                try:
                    x, y = self.getPosition(key,number)
                except:
                    logThis("Error getting position (error code 1641)")
                d.ellipse([(x-avatarHalf,y-avatarHalf),(x+avatarHalf,y+avatarHalf)],fill=(255,0,0))

        board.save("resources/games/monopolyBoards/monopolyBoard"+channel+".png")


    def getPosition(self, positionNumber, number):
        x, y = 0, 0
        if positionNumber == 0 or positionNumber >= 30:
            x = math.floor(largeSpace/2)
        elif positionNumber > 0 and positionNumber < 10:
            x = math.floor(largeSpace - (smallSpace/2)) + (smallSpace*positionNumber)
        elif positionNumber >= 10 and positionNumber <= 20:
            x = w - math.floor(largeSpace/2)
        elif positionNumber > 20 and positionNumber < 30:
            x = w - math.floor(largeSpace - (smallSpace/2)) - (smallSpace*(positionNumber - 20))

        if positionNumber >= 0 and positionNumber <= 10:
            y = math.floor(largeSpace/2)
        elif positionNumber > 10 and positionNumber < 20:
            y = math.floor(largeSpace - (smallSpace/2)) + (smallSpace*(positionNumber-10))
        elif positionNumber >= 20 and positionNumber <= 30:
            y = h - math.floor(largeSpace/2)
        elif positionNumber > 30:
            y = h - math.floor(largeSpace - (smallSpace/2)) - (smallSpace*(positionNumber - 30))

        if number%2 == 1:
            x -= avatarBuffer + avatarSize

        if math.floor(number/2) == 1:
            y += avatarBuffer + avatarSize
        elif math.floor(number/2) == 2:
            y -= avatarBuffer + avatarSize

        x += avatarSize

        return x, y


