import discord, asyncio
from discord.ext import commands

from funcs import logThis, triviaAnswer, triviaCountPoints, triviaStart, deleteGame, checkBalance, giveMoney, parseBlackjack, parseInvest, fiar, runMonopoly, runHex, runHangman

class GamesCog(commands.Cog):

    def __init__(self,client):
        """Runs game stuff."""
        self.client = client

    # Checks user balance
    @commands.command(aliases = ["b"])
    async def balance(self, ctx):
        response = checkBalance("#"+str(ctx.message.author.id))
        if response == 1:
            new_message = ctx.message.author.display_name + " has " + str(response) + " GwendoBuck"
        else:
            new_message = ctx.message.author.display_name + " has " + str(response) + " GwendoBucks"
        await ctx.send(new_message)

    # Gives another user an amount of GwendoBucks
    @commands.command()
    async def give(self, ctx, *, content):
        commands = content.split(" ")
        if len(commands) == 2:
            amount = int(commands[1])
            response = giveMoney("#"+str(ctx.message.author.id),commands[0],amount)
            await ctx.send(response)
        else:
            logThis("I didn't understand that (error code 1222)",str(ctx.message.channel.id))
            await ctx.send("I didn't understand that (error code 1222)")

    # Invest GwendoBucks in the stock market
    @commands.command(aliases=["i"])
    async def invest(self, ctx, *, content = "check"):
        response = parseInvest(content,"#"+str(ctx.message.author.id),self.client.finnhubClient)
        if response.startswith("**"):
            responses = response.split("\n")
            em = discord.Embed(title=responses[0],description="\n".join(responses[1:]),colour=0x00FF00)
            await ctx.send(embed=em)
        else:
            await ctx.send(response)

    # Runs a game of trivia
    @commands.command()
    async def trivia(self, ctx, *, content = ""):
        if content == "":
            question, answers, correctAnswer = triviaStart(str(ctx.message.channel.id))
            if answers != "":
                results = "**"+question+"**\n"
                for x, answer in enumerate(answers):
                    results += chr(x+97) + ") "+answer+"\n"

                await ctx.send(results)

                await asyncio.sleep(60)

                triviaCountPoints(str(ctx.message.channel.id))

                deleteGame("trivia questions",str(ctx.message.channel.id))

                logThis("Time's up for the trivia question",str(ctx.message.channel.id))
                await ctx.send("Time's up The answer was \""+chr(correctAnswer)+") "+answers[correctAnswer-97]+"\". Anyone who answered that has gotten 1 GwendoBuck")
            else:
                await ctx.send(question)

        elif content in ["a","b","c","d"]:
            response = triviaAnswer("#"+str(ctx.message.author.id),str(ctx.message.channel.id),content)
            if response.startswith("Locked in "):
                await ctx.message.add_reaction("👍")
            else:
                await ctx.send(response)
        else:
            logThis("I didn't understand that (error code 1101)",str(ctx.message.channel.id))
            await ctx.send("I didn't understand that (error code 1101)")

    # Runs a game of blackjack
    @commands.command(aliases = ["bj"])
    async def blackjack(self, ctx, *, content = ""):
        await parseBlackjack(content,ctx)

    # Runs a game of Connect four
    @commands.command(aliases = ["fiar","connect4","connectfour","4iar","4inarow"])
    async def fourinarow(self, ctx, *, content = ""):
        await fiar(ctx.message.channel,content,"#"+str(ctx.message.author.id))

    # Runs a game of Hex
    @commands.command(name="hex")
    async def hexCommand(self, ctx, *, content = ""):
        await runHex(ctx.message.channel,content,"#"+str(ctx.message.author.id))

    # Runs a game of Monopoly
    @commands.command(aliases = ["m","mon","mono"])
    async def monopoly(self, ctx, *, content = ""):
        await runMonopoly(ctx.message.channel,content,"#"+str(ctx.message.author.id))

    # Runs a game of Hangman
    @commands.command(aliases = ["hm"])
    async def hangman(self, ctx, *, content = "start"):
        await runHangman(ctx.message.channel,"#"+str(ctx.message.author.id),self.client.credentials.wordnikKey,content)

def setup(client):
    client.add_cog(GamesCog(client))