import discord, codecs, string
from discord.ext import commands

from funcs import logThis, helloFunc, roll_dice, imageFunc, movieFunc, cap, findWikiPage

class MiscCog(commands.Cog):

    def __init__(self,client):
        """Runs misc commands."""
        self.client = client
        self.client.remove_command("help")
        self.generator = client.generator
        self.bedreNetflix = client.bedreNetflix
        self.nerdShit = client.nerdShit

    @commands.command(name = "help")
    async def helpCommand(self, ctx, *, content = ""):
        if content == "":
            with codecs.open("resources/help/help.txt",encoding="utf-8") as f:
                text = f.read()
            em = discord.Embed(title = "Help", description = text,colour = 0x59f442)
            await ctx.send(embed = em)
        else:
            logThis(f"Looking for help-{content}.txt",str(ctx.message.channel.id))
            with codecs.open(f"resources/help/help-{content}.txt",encoding="utf-8") as f:
                text = f.read()
            em = discord.Embed(title = content.capitalize(), description = text,colour = 0x59f442)
            await ctx.send(embed = em)

    # Sends the bot's latency
    @commands.command()
    async def ping(self, ctx):
        await ctx.send(f"Pong!\nLatency is {round(self.client.latency * 1000)} ms")

    # Logs whatever is written
    @commands.command(hidden = True)
    async def log(self, ctx, *, content):
        logThis(content,str("Logged by "+ctx.message.author.display_name))

    # Restarts the bot
    @commands.command(hidden = True,aliases=["stop"])
    async def restart(self, ctx):
        if "#"+str(ctx.message.author.id) in ["#266269899859427329", "#380732645602230272"]:
            await ctx.send("Pulling git repo and restarting...")

            self.client.funcs.stopServer()

            logThis("Logging out.")
            await self.client.logout()
        else:
            logThis(f"{ctx.message.author.display_name} tried to stop me! (error code 201)",str(ctx.message.channel.id))
            await ctx.send(f"I don't think I will, {ctx.message.author.display_name} (error code 201)")

    @commands.command(aliases = ["thankyou", "thanku", "thanks"])
    async def thank(self, ctx):
        await ctx.send("You're welcome :blush:")

    # Sends a friendly message
    @commands.command(aliases = ["hi","howdy"])
    async def hello(self, ctx):
        await ctx.send(helloFunc(ctx.message.author.display_name))

    # Rolls dice
    @commands.command()
    async def roll(self, ctx, *, content = "1d20"):
        await ctx.send(roll_dice(ctx.message.author.display_name,content))

    # Sends an image of the Senkulpa map
    @commands.command(name="map")
    async def mapCommand(self, ctx):
        await ctx.send("https://i.imgur.com/diMXXJs.jpg")

    # Sends a random image
    @commands.command(aliases = ["img"])
    async def image(self, ctx):
        randomImage = imageFunc()
        await ctx.send(randomImage)

    # Finds a random movie
    @commands.command()
    async def movie(self,ctx):
        async with ctx.typing():
            title, plot, cover, cast = movieFunc()
            if title == "error":
                await ctx.send("An error occurred. Try again (error code "+plot+")")
            else:
                try:
                    embed = discord.Embed(title=title, description=plot, color=0x24ec19)
                    embed.set_thumbnail(url=cover)
                    embed.add_field(name="Cast", value=cast,inline = True)
                    await ctx.send(embed = embed)
                except:
                    logThis("Error embedding (error code 805)")

    # Generates a random name
    @commands.command()
    async def name(self, ctx):
        await ctx.send(self.generator.nameGen())

    # Generates a random tavern name
    @commands.command()
    async def tavern(self, ctx):
        await ctx.send(self.generator.tavernGen())

    # Sets the game Gwendolyn's playing
    @commands.command()
    async def game(self, ctx, *, content):
        gamePlaying = cap(content)
        game = discord.Game(gamePlaying)
        await self.client.change_presence(activity=game)

    # Finds a page on the Senkulpa wiki
    @commands.command(aliases = ["wikia"])
    async def wiki(self, ctx, *, content):
        async with ctx.message.channel.typing():
            command = string.capwords(content)
            title, content, thumbnail = findWikiPage(command)
            if title != "":
                logThis("Sending the embedded message",str(ctx.message.channel.id))
                content += "\n[Læs mere](https://senkulpa.fandom.com/da/wiki/"+title.replace(" ","_")+")"
                embed = discord.Embed(title = title, description = content, colour=0xDEADBF)
                if thumbnail != "":
                    embed.set_thumbnail(url=thumbnail)

                await ctx.send(embed = embed)
            else:
                await ctx.send(content)

    #Searches for movie and adds it to Bedre Netflix
    @commands.command(aliases = ["rm","addmovie","am"])
    async def requestmovie(self, ctx, *, content):
        await self.bedreNetflix.requestMovie(ctx,content)

    #Searches for show and adds it to Bedre Netflix
    @commands.command(aliases = ["rs","addshow","as","addseries"])
    async def requestshow(self, ctx, *, content):
        await self.bedreNetflix.requestShow(ctx,content)

    #Returns currently downloading torrents
    @commands.command(aliases = ["downloads"])
    async def downloading(self, ctx, *, content = "-d"):
        await self.bedreNetflix.downloading(ctx, content)

    #Looks up on Wolfram Alpha
    @commands.command()
    async def wolf(self, ctx, *, content):
        await self.nerdShit.wolfSearch(ctx,content)

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