import discord, asyncio
from discord.ext import commands

from funcs import logThis

class GamesCog(commands.Cog):

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

    # Checks user balance
    @commands.command(aliases = ["b"])
    async def balance(self, ctx):
        response = self.bot.money.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(" ")
        amount = int(commands[-1])
        username = " ".join(commands[:-1])
        if self.bot.funcs.getID(username) == None:
            async for member in ctx.guild.fetch_members(limit=None):
                if member.display_name.lower() == username.lower():
                    username = member.display_name
                    userID = "#" + str(member.id)
                    self.bot.database["users"].insert_one({"_id":userID,"user name":username,"money":0})
        response = self.bot.money.giveMoney("#"+str(ctx.message.author.id),username,amount)
        await ctx.send(response)

    # Invest GwendoBucks in the stock market
    @commands.command(aliases=["i"])
    async def invest(self, ctx, *, content = "check"):
        response = self.bot.invest.parseInvest(content,"#"+str(ctx.message.author.id))
        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 = self.bot.trivia.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)

                self.bot.trivia.triviaCountPoints(str(ctx.message.channel.id))

                self.bot.funcs.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 = self.bot.trivia.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 self.bot.blackjack.parseBlackjack(content,ctx)

    # Runs a game of Connect four
    @commands.command(aliases = ["fiar","connect4","connectfour","4iar","4inarow"])
    async def fourinarow(self, ctx, *, content = ""):
        await self.bot.gameLoops.fiar(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 self.bot.gameLoops.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 self.bot.gameLoops.runHangman(ctx.message.channel,"#"+str(ctx.message.author.id),content)

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

    # Runs a game of Love Letter
    @commands.command(aliases = ["ll"])
    async def loveletter(self, ctx, *, content = ""):
        await self.bot.gameLoops.runLoveletter(ctx.message.channel,content,"#"+str(ctx.message.author.id),ctx.message.author)

    # Runs a game of Werewolf
    @commands.command()
    async def werewolf(self,ctx, *,content = "start"):
        await self.bot.werewolf.parseWerewolf(ctx,content.lower())

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