import os

import requests
import discord
import wolframalpha
from PIL import Image, ImageDraw, ImageFont

class NerdShit():
  def __init__(self, bot):
    """Runs misc commands."""
    self.bot = bot

  async def wolf_search(self,ctx,content):
    await self.bot.defer(ctx)
    font = ImageFont.truetype('gwendolyn/resources/fonts/times-new-roman.ttf', 20)
    self.bot.log("Requesting data")
    bot = wolframalpha.Client(self.bot.credentials["wolfram_alpha_key"])
    res = bot.query(content)

    self.bot.log("Processing data")
    titles = []
    pods = []
    if int(res.numpods) > 0:
      for pod in res.pods:
        titles += [pod.title]
        for i, sub in enumerate(pod.subpods):
          pods += [sub]
          if i > 0:
            titles += [""]

      pod_chunks = [pods[x:x+2] for x in range(0, len(pods), 2)]
      title_chunks = [titles[x:x+2] for x in range(0, len(titles), 2)]
      await ctx.send(f"Response for \"{content}\"")

      for i, chunk in enumerate(pod_chunks):
        width = 0
        for title in title_chunks[i]:
          width = max(width,font.getsize(title)[0])
        height = 5
        heights = []
        for count, pod in enumerate(chunk):
          heights += [height]
          width = max(width,int(pod.img['@width']))
          if title_chunks[i][count] == "":
            place_for_text = 0
          else:
            place_for_text = 30
          height += int(pod.img["@height"]) + 10 + place_for_text

        width += 10
        height += 5
        wolf_image = Image.new("RGB",(width,height),color=(255,255,255))

        for count, pod in enumerate(chunk):
          response = requests.get(pod.img["@src"])
          file = open("gwendolyn/resources/wolfTemp.png", "wb")
          file.write(response.content)
          file.close()
          old_image = Image.open("gwendolyn/resources/wolfTemp.png")
          old_size = old_image.size
          if title_chunks[i][count] == "":
            place_for_text = 0
          else:
            place_for_text = 30
          new_size = (width,int(old_size[1]+10+place_for_text))
          new_image = Image.new("RGB",new_size,color=(255,255,255))
          new_image.paste(old_image, (int((int(old_size[0]+10)-old_size[0])/2),int(((new_size[1]-place_for_text)-old_size[1])/2)+place_for_text))
          if title_chunks[i][count] != "":
            drawer = ImageDraw.Draw(new_image,"RGB")
            drawer.text((5,7),title_chunks[i][count],font=font,fill=(150,150,150))

          wolf_image.paste(new_image,(0,heights[count]))
          new_image.close()
          old_image.close()
          count += 1

        wolf_image.save("gwendolyn/resources/wolf.png")
        wolf_image.close()
        await ctx.channel.send(file = discord.File("gwendolyn/resources/wolf.png"))

        os.remove("gwendolyn/resources/wolf.png")
        os.remove("gwendolyn/resources/wolfTemp.png")
    else:
      self.bot.log("No returned data")
      await ctx.send("Could not find anything relating to your search")
