import datetime  # Used in hello_func

from interactions import SlashContext, Embed, SlashCommand

from .name_generator import NameGenerator

from .roll import DieRoller

def gen_help_text(commands: list[SlashCommand]):
  return '\n'.join(sorted([f"`/{i.name}`\t— {i.description}" for i in commands]))

class Other():
  def __init__(self, bot):
    self.bot = bot
    self._name_generator = NameGenerator()
    self._roller = DieRoller()

  # Responds with a greeting of a time-appropriate maner
  async def hello_func(self, ctx: SlashContext):
    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)

  async def help_func(self, ctx: SlashContext, command: str):
    if command == "":
      text = gen_help_text([i for i in self.bot.application_commands if isinstance(i,SlashCommand)])
      embed = Embed(title = "Help", description = text,color = 0x59f442)
      await ctx.send(embed = embed)
    else:
      self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
      try:
        with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as file_pointer:
          text = file_pointer.read()
        embed = Embed(title = command.capitalize(), description = text,color = 0x59f442)
        await ctx.send(embed = embed)
      except:
        await ctx.send(f"Could not find a help file for the command '/{command}'")

  async def generate_name(self, ctx: SlashContext):
    await ctx.send(self._name_generator.generate())

  async def roll_dice(self, ctx: SlashContext, dice: str):
    try:
      roll = self._roller.roll(dice)
      await ctx.send(f":game_die:Rolling dice `{dice}`\n{roll}")
    except:
      await ctx.send("There was an error in the rolling")
