import random  # Used in movie_func
import datetime  # Used in hello_func
import urllib  # Used in image_func
import ast

import imdb  # Used in movie_func
import discord  # Used in movie_func
import lxml  # Used in image_func
import fandom  # Used in find_wiki_page
import d20  # Used in roll_dice

from .plex import Plex
from .nerd_shit import NerdShit
from .generators import Generators

fandom.set_lang("da")
fandom.set_wiki("senkulpa")

class MyStringifier(d20.MarkdownStringifier):
  def _str_expression(self, node):
    if node.comment is None:
      result_text = "Result"
    else:
      result_text = node.comment.capitalize()

    return f"**{result_text}**: {self._stringify(node.roll)}\n**Total**: {int(node.total)}"

class Other():
  def __init__(self, bot):
    self.bot = bot
    self.plex = Plex(self.bot)
    self.nerd_shit = NerdShit(self.bot)
    self.generators = Generators(self.bot)

  # Picks a random movie and returns information about it
  async def movie_func(self, ctx):
    await self.bot.defer(ctx)

    self.bot.log("Creating IMDb object")
    imdb_client = imdb.IMDb()

    self.bot.log("Picking a movie")
    with open("gwendolyn/resources/movies.txt", "r") as file_pointer:
      movie_list = file_pointer.read().split("\n")
    movie_name = random.choice(movie_list)

    self.bot.log(f"Searching for {movie_name}")
    search_result = imdb_client.search_movie(movie_name)

    self.bot.log("Getting the data")
    movie = search_result[0]
    imdb_client.update(movie)

    self.bot.log("Successfully ran /movie")

    title = movie["title"]
    plot = movie['plot'][0].split("::")[0]
    cover = movie['cover url'].replace("150","600").replace("101","404")
    cast = ", ".join([i["name"] for i in movie['cast'][:5]])
    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)

  # Responds with a greeting of a time-appropriate maner
  async def hello_func(self, ctx):
    def time_in_range(start, end, i):
      # Return true if i is in the range [start, end]
      if start <= end:
        return start <= i <= end
      else:
        return start <= i or i <= end

    author = ctx.author.display_name
    now = datetime.datetime.now()
    if time_in_range(now.replace(hour=5, minute=0, second=0, microsecond=0),now.replace(hour=10, minute=0, second=0, microsecond=0), now):
      send_message = "Good morning, "+str(author)
    elif time_in_range(now.replace(hour=13, minute=0, second=0, microsecond=0),now.replace(hour=18, minute=0, second=0, microsecond=0), now):
      send_message = "Good afternoon, "+str(author)
    elif time_in_range(now.replace(hour=18, minute=0, second=0, microsecond=0),now.replace(hour=22, minute=0, second=0, microsecond=0), now):
      send_message = "Good evening, "+str(author)
    elif time_in_range(now.replace(hour=22, minute=0, second=0, microsecond=0),now.replace(hour=23, minute=59, second=59, microsecond=0), now):
      send_message = "Good night, "+str(author)
    else:
      send_message = "Hello, "+str(author)

    await ctx.send(send_message)

  # Finds a random picture online
  async def image_func(self, ctx):
    # Picks a type of camera, which decides the naming scheme
    cams = ("one","two","three","four")
    cam = random.choice(cams)
    self.bot.log("Chose cam type "+cam)
    if cam == "one":

      search = "img_" + ''.join(
        [str(random.randint(0,9)) for _ in range(4)]
      )
    elif cam == "two":
      year = str(random.randint(2012,2016))
      month = str(random.randint(1,12)).zfill(2)
      day = str(random.randint(1,29)).zfill(2)
      search = f"IMG_{year}{month}{day}"
    elif cam == "three":
      search = f"IMAG_{str(random.randint(1,500)).zfill(4)}"
    elif cam == "four":
      search = "DSC_" + ''.join(
        [str(random.randint(0,9)) for _ in range(4)]
      )

    self.bot.log("Searching for "+search)

    # Searches for the image and reads the resulting web page
    page = urllib.request.urlopen("https://www.bing.com/images/search?q="+search+"&safesearch=off")
    read = page.read()
    tree = lxml.etree.HTML(read)
    images = tree.xpath('//a[@class = "iusc"]/@m')

    if len(images) == 0:
      await ctx.send("Found no images")
    else:
      # Picks an image
      number = random.randint(1,len(images))-1
      image = ast.literal_eval(str(images[number]))
      image_url = image["murl"]

      self.bot.log("Picked image number "+str(number))

      # Returns the image
      self.bot.log("Successfully returned an image")

      await ctx.send(image_url)

  # Finds a page from the Senkulpa Wikia
  async def find_wiki_page(self, ctx, search : str):
    await self.bot.defer(ctx)
    found_page = False

    if search != "":
      self.bot.log("Trying to find wiki page for "+search)
      search_results = fandom.search(search)
      if len(search_results) > 0:
        found_page = True
        search_result = search_results[0]
      else:
        self.bot.log("Couldn't find the page")
        await ctx.send("Couldn't find page")
    else:
      found_page = True
      self.bot.log("Searching for a random page")
      search_result = fandom.random()

    if found_page:
      self.bot.log(f"Found page \"{search_result[0]}\"")
      page = fandom.page(pageid = search_result[1])
      content = page.summary

      images = page.images
      if len(images) > 0:
        image = images[0]
      else:
        image = ""
      self.bot.log("Sending the embedded message",str(ctx.channel_id))
      content += f"\n[Læs mere]({page.url})"
      embed = discord.Embed(title = page.title, description = content, colour=0xDEADBF)
      if image != "":
        embed.set_thumbnail(url=image)

      await ctx.send(embed = embed)

  async def roll_dice(self, ctx, roll_string):
    user = ctx.author.display_name
    while len(roll_string) > 1 and roll_string[0] == " ":
      roll_string = roll_string[1:]

    roll = d20.roll(roll_string, allow_comments=True, stringifier=MyStringifier())
    await ctx.send(f"{user} :game_die:\n{roll}")

  async def help_func(self, ctx, command):
    if command == "":
      with open("gwendolyn/resources/help/help.txt",encoding="utf-8") as file_pointer:
        text = file_pointer.read()
      embed = discord.Embed(title = "Help", description = text,colour = 0x59f442)
      await ctx.send(embed = embed)
    else:
      self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
      with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as file_pointer:
        text = file_pointer.read()
      embed = discord.Embed(title = command.capitalize(), description = text,colour = 0x59f442)
      await ctx.send(embed = embed)

