import discord, json, os, asyncio

from .blackjack import blackjackContinue, blackjackSplit, blackjackShuffle, blackjackStart, blackjackFinish, blackjackPlayerDrawHand, blackjackHit, blackjackStand, blackjackDouble
from funcs import logThis

# Loop of blackjack game rounds
async def blackjackLoop(channel,gameRound,gameID):
    logThis("Loop "+str(gameRound),str(channel.id))

    with open("resources/games/oldImages/blackjack"+str(channel.id), "r") as f:
        oldImage = await channel.fetch_message(int(f.read()))

    new_message, allStanding, gamedone = blackjackContinue(str(channel.id))
    if new_message != "":
        logThis(new_message,str(channel.id))
        await channel.send(new_message)
    if gamedone == False:
        await oldImage.delete()
        oldImage = await channel.send(file = discord.File("resources/games/blackjackTables/blackjackTable"+str(channel.id)+".png"))
        with open("resources/games/oldImages/blackjack"+str(channel.id), "w") as f:
            f.write(str(oldImage.id))

    try:
        if allStanding:
            await asyncio.sleep(5)
        else:
            await asyncio.sleep(120)
    except:
        logThis("Loop "+str(gameRound)+" interrupted (error code 1321)")

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

    if str(channel.id) in data["blackjack games"]:
        realRound = data["blackjack games"][str(channel.id)]["round"]
        realGameID = data["blackjack games"][str(channel.id)]["id"]

        if gameRound == realRound and realGameID == gameID:
            if gamedone == False:
                logThis("Loop "+str(gameRound)+" calling blackjackLoop()",str(channel.id))
                await blackjackLoop(channel,gameRound+1,gameID)
            else:
                try:
                    new_message = blackjackFinish(str(channel.id))
                except:
                    logThis("Something fucked up (error code 1310)")
                await channel.send(new_message)
        else:
            logThis("Ending loop on round "+str(gameRound),str(channel.id))
    else:
        logThis("Ending loop on round "+str(gameRound),str(channel.id))

async def parseBlackjack(content, ctx):
    # Blackjack shuffle variables
    blackjackMinCards = 50
    blackjackDecks = 4

    channel = ctx.message.channel.id
    # Starts the game
    if content == "":
        cardsLeft = 0
        if os.path.exists("resources/games/blackjackCards/"+str(channel)+".txt"):
            with open("resources/games/blackjackCards/"+str(channel)+".txt","r") as f:
                for _ in f:
                    cardsLeft += 1

        # Shuffles if not enough cards
        if cardsLeft < blackjackMinCards:
            blackjackShuffle(blackjackDecks,str(channel))
            logThis("Shuffling the blackjack deck...",str(channel))
            await ctx.send("Shuffling the deck...")

        new_message = blackjackStart(str(channel))
        if new_message == "started":

            new_message = "Blackjack game started. Use \"!blackjack bet [amount]\" to enter the game within the next 30 seconds."
            await ctx.send(new_message)
            oldImage = await ctx.send(file = discord.File("resources/games/blackjackTables/blackjackTable"+str(channel)+".png"))

            with open("resources/games/oldImages/blackjack"+str(channel), "w") as f:
                f.write(str(oldImage.id))

            await asyncio.sleep(30)

            gamedone = False

            with open("resources/games/games.json", "r") as f:
                data = json.load(f)
                if len(data["blackjack games"][str(channel)]["user hands"]) == 0:
                    gamedone = True
                    await ctx.send("No one entered the game. Ending the game.")
                gameID = data["blackjack games"][str(channel)]["id"]

            # Loop of game rounds
            if gamedone == False:
                logThis("!blackjack calling blackjackLoop()",str(channel))
                await blackjackLoop(ctx.message.channel,1,gameID)
            else:
                new_message = blackjackFinish(str(channel))
                await ctx.send(new_message)
        else:
            await ctx.send(new_message)

    # Entering game and placing bet
    elif content.startswith("bet"):
        commands = content.split(" ")
        amount = int(commands[1])
        response = blackjackPlayerDrawHand(str(channel),"#"+str(ctx.message.author.id),amount)
        await ctx.send(response)

    # Hitting
    elif content.startswith("hit"):
        if content == "hit":
            response = blackjackHit(str(channel),"#"+str(ctx.message.author.id))
        else:
            commands = content.split(" ")
            try:
                handNumber = int(commands[1])
            except:
                handNumber = 0
            response = blackjackHit(str(channel),"#"+str(ctx.message.author.id),handNumber)

        if response.startswith("accept"):
            await ctx.message.add_reaction("👍")
            try:
                if response[6] == "T":
                    with open("resources/games/games.json", "r") as f:
                        gameID = json.load(f)["blackjack games"][str(channel)]["id"]
                    logThis("Hit calling blackjackLoop()",str(channel))
                    await blackjackLoop(ctx.message.channel,int(response[7:])+1,gameID)
            except:
                logThis("Something fucked up (error code 1320)",str(channel))
        else:
            await ctx.send(response)


    # Standing
    elif content.startswith("stand"):
        if content == "hit":
            response = blackjackStand(str(channel),"#"+str(ctx.message.author.id))
        else:
            commands = content.split(" ")
            try:
                handNumber = int(commands[1])
            except:
                handNumber = 0
            response = blackjackStand(str(channel),"#"+str(ctx.message.author.id),handNumber)

        if response.startswith("accept"):
            await ctx.message.add_reaction("👍")
            try:
                if response[6] == "T":
                    with open("resources/games/games.json", "r") as f:
                        gameID = json.load(f)["blackjack games"][str(channel)]["id"]
                    logThis("Stand calling blackjackLoop()",str(channel))
                    await blackjackLoop(ctx.message.channel,int(response[7:])+1,gameID)
            except:
                logThis("Something fucked up (error code 1320)",str(channel))
        else:
            await ctx.send(response)

    # Doubling bet
    elif content.startswith("double"):
        commands = content.split(" ")
        try:
            handNumber = int(commands[1])
        except:
            handNumber = 0
        response, roundDone = blackjackDouble(str(channel),"#"+str(ctx.message.author.id),handNumber)

        await ctx.send(response)

        try:
            if roundDone[0] == "T":
                with open("resources/games/games.json", "r") as f:
                    gameID = json.load(f)["blackjack games"][str(channel)]["id"]
                logThis("Double calling blackjackLoop()",str(channel))
                await blackjackLoop(ctx.message.channel,int(roundDone[1:])+1,gameID)
        except:
            logThis("Something fucked up (error code 1320)",str(channel))

    # Splitting hand
    elif content.startswith("split"):
        commands = content.split(" ")
        try:
            handNumber = int(commands[1])
        except:
            handNumber = 0
        response, roundDone = blackjackSplit(str(channel),"#"+str(ctx.message.author.id),handNumber)

        await ctx.send(response)

        try:
            if roundDone[0] == "T":
                with open("resources/games/games.json", "r") as f:
                    gameID = json.load(f)["blackjack games"][str(channel)]["id"]
                logThis("Split calling blackjackLoop()",str(channel))
                await blackjackLoop(ctx.message.channel,int(roundDone[1:])+1,gameID)
        except:
            logThis("Something fucked up (error code 1320)")

    # Returning current hi-lo value
    elif content.startswith("hilo") and "#"+str(ctx.message.author.id) == "#266269899859427329":
        if os.path.exists("resources/games/blackjackCards/"+str(channel)+".txt"):
            with open("resources/games/hilo/"+str(channel)+".txt", "r") as f:
                data = f.read()
        else:
            data = "0"
        await ctx.send(data)

    # Shuffles the blackjack deck
    elif content.startswith("shuffle"):
        blackjackShuffle(blackjackDecks,str(channel))
        logThis("Shuffling the blackjack deck...",str(channel))
        await ctx.send("Shuffling the deck...")


    # Tells you the amount of cards left
    elif content.startswith("cards"):
        cardsLeft = 0
        if os.path.exists("resources/games/blackjackCards/"+str(channel)+".txt"):
            with open("resources/games/blackjackCards/"+str(channel)+".txt","r") as f:
                for _ in f:
                    cardsLeft += 1

        decksLeft = round(cardsLeft/52,1)
        await ctx.send(str(cardsLeft)+" cards, "+str(decksLeft)+" decks")

    else:
        logThis("Not a command (error code 1301)")
        await ctx.send("I didn't quite understand that (error code 1301)")
