import random
import re
import string
import json

with open("gwendolyn/resources/star_wars/starwarsskills.json", "r") as f:
  skill_data = json.load(f)

class StarWarsRoll():
  def __init__(self, bot):
    self.bot = bot

  # Rolls the specified dice
  def roll(self, abi : int = 1, prof : int = 0, dif : int = 3, cha : int = 0, boo : int = 0, setb : int = 0, force : int = 0):
    result = ""
    dice_result = []
    for _ in range(abi):
      choice = random.choice(["","S","S","SS","A","A","SA","AA"])
      result += choice
      dice_result.append("abi"+choice)

    for _ in range(prof):
      choice = random.choice(["","S","S","SS","SS","A","SA","SA","SA","AA","AA","R"])
      result += choice
      dice_result.append("prof"+choice)

    for _ in range(dif):
      choice = random.choice(["","F","FF","H","H","H","HH","FH"])
      result += choice
      dice_result.append("dif"+choice)

    for _ in range(cha):
      choice = random.choice(["","F","F","FF","FF","H","H","FH","FH","HH","HH","D"])
      result += choice
      dice_result.append("cha"+choice)

    for _ in range(boo):
      choice = random.choice(["","","S","SA","AA","A"])
      result += choice
      dice_result.append("boo"+choice)

    for _ in range(setb):
      choice = random.choice(["","","F","F","H","H"])
      result += choice
      dice_result.append("setb"+choice)

    for _ in range (force):
      choice = random.choice(["B","B","B","B","B","B","BB","L","L","LL","LL","LL"])
      result += choice
      dice_result.append("force"+choice)

    return result, dice_result

  # Lets dice cancel each other out
  def simplify(self, result : str):
    self.bot.log("Simplifying "+result)
    simp = ""
    success = (result.count('S') + result.count('R')) - (result.count('F') + result.count('D'))
    advantage = result.count('A') - result.count('H')
    result = re.sub("S|A|F|H","",result)

    if success > 0:
      for _ in range(success):
        simp += "S"
    elif success < 0:
      for _ in range(abs(success)):
        simp += "F"

    if advantage > 0:
      for _ in range(advantage):
        simp += "A"
    elif advantage < 0:
      for _ in range(abs(advantage)):
        simp += "H"

    simp += result

    return simp

  # Returns emoji that symbolize the dice results
  def dice_result_to_emoji(self, dice_results : list):
    emoji = ""
    for result in dice_results:
      if result == "abiA":
        emoji += "<:abil1a:695267684476125264> "
      elif result == "abiSA":
        emoji += "<:abil1a1s:695267684484513842> "
      elif result == "abiS":
        emoji += "<:abil1s:695267684514005013> "
      elif result == "abiAA":
        emoji += "<:abil2a:695267684547428352> "
      elif result == "abiSS":
        emoji += "<:abil2s:695267684761206914> "
      elif result == "abi":
        emoji += "<:abilbla:695267684660674602> "

      elif result == "profA":
        emoji += "<:prof1a:695267685361123338> "
      elif result == "profSA":
        emoji += "<:prof1a1s:695267685067653140> "
      elif result == "profR":
        emoji += "<:prof1r:695267685067522088> "
      elif result == "profS":
        emoji += "<:prof1s:695267684899881012> "
      elif result == "profAA":
        emoji += "<:prof2a:695267684996218982> "
      elif result == "profSS":
        emoji += "<:prof2s:695267684878647327> "
      elif result == "prof":
        emoji += "<:profbla:695267684698292235> "

      elif result == "difF":
        emoji += "<:dif1f:695267684924915804> "
      elif result == "difH":
        emoji += "<:dif1h:695267684908138506> "
      elif result == "difFH":
        emoji += "<:dif1h1f:695267684908269678> "
      elif result == "difFF":
        emoji += "<:dif2f:695267684924784680> "
      elif result == "difHH":
        emoji += "<:dif2h:695267685071585340> "
      elif result == "dif":
        emoji += "<:difbla:695267685000544276> "

      elif result == "chaD":
        emoji += "<:cha1d:695267684962533447> "
      elif result == "chaF":
        emoji += "<:cha1f:695267684601954346> "
      elif result == "chaH":
        emoji += "<:cha1h:695267685046681620> "
      elif result == "chaFH":
        emoji += "<:cha1h1f:695267685063327784> "
      elif result == "chaFF":
        emoji += "<:cha2f:695267684832641097> "
      elif result == "chaHH":
        emoji += "<:cha2h:695267684631183381> "
      elif result == "cha":
        emoji += "<:chabla:695267684895686787> "

      elif result == "booA":
        emoji += "<:boo1a:695267684975116329> "
      elif result == "booSA":
        emoji += "<:boo1a1s:695267684970922024> "
      elif result == "booS":
        emoji += "<:boo1s:695267684979441714> "
      elif result == "booAA":
        emoji += "<:boo2a:695267685100945488> "
      elif result == "boo":
        emoji += "<:boobla:695267684757012550> "

      elif result == "setbF":
        emoji += "<:set1f:695267685054939197> "
      elif result == "setbH":
        emoji += "<:set1h:695267685147082802> "
      elif result == "setb":
        emoji += "<:setbla:695267685151408169> "

      elif result == "forceB":
        emoji += "<:for1b:695267684593434677> "
      elif result == "forceL":
        emoji += "<:for1l:695267684606148640> "
      elif result == "forceBB":
        emoji += "<:for2b:695267684903944303> "
      elif result == "forceLL":
        emoji += "<:for2l:695267684992024626> "

    return emoji

  # Returns emoji that symbolize the results of the dice rolls
  def result_to_emoji(self, result : str):
    emoji = ""
    for char in result:
      if char == 'S':
        emoji += "<:success:826026925280854026> "
      elif char == 'A':
        emoji += "<:advantage:826026925515604009> "
      elif char == 'R':
        emoji += "<:triumph:826026925319127070> "
      elif char == 'F':
        emoji += "<:failure:826026925288980511> "
      elif char == 'H':
        emoji += "<:threat:826026925280985108> "
      elif char == 'D':
        emoji += "<:despair:826026925272203294> "
      elif char == 'L':
        emoji += "<:light:826026925059211295>"
      elif char == 'B':
        emoji += "<:dark:826026925289373717>"

    return emoji

  # Converts emoji into letters
  def emoji_to_result(self, emoji : str):
    result = ""
    for char in emoji:
      if char == "<:light:691010089905029171>":
        emoji += 'L'
      if char == "<:dark:691010101901000852>":
        emoji += 'B'

    return result

  # Returns emoji that symbolize the dice
  def dice_to_emoji(self, dice : list):
    emoji = ""

    for _ in range(dice[0]):
      emoji += "<:ability:690974213397282826> "
    for _ in range(dice[1]):
      emoji += "<:proficiency:690973435354153071> "
    for _ in range(dice[2]):
      emoji += "<:difficulty:690973992470708296> "
    for _ in range(dice[3]):
      emoji += "<:challenge:690973419906400306> "
    for _ in range(dice[4]):
      emoji += "<:boost:690972178216386561> "
    for _ in range(dice[5]):
      emoji += "<:setback:690972157890658415> "
    for _ in range(dice[6]):
      emoji += "<:force:690973451883774013> "

    return emoji

  # Rolls for obligation
  def obligation_roll(self):
    self.bot.log("Rolling for obligation")
    data = self.bot.database["starwarscharacters"]

    table = []

    for character in data:
      for obligation in data[character]["Obligations"]:
        for _ in range(data[character]["Obligations"][obligation]):
          table.append(data[character]["Name"]+", "+obligation)

    while len(table) < 100:
      table.append("Nothing")

    return random.choice(table)

  # Rolls for critical injury
  async def crit_roll(self, ctx, addington : int):
    difficulty_die = "<:difficulty:690973992470708296>"
    setback_die = "<:setback:690972157890658415>"
    boost_die = "<:boost:690972178216386561>"
    roll = random.randint(1,100) + addington
    injuries = [
      "**Minor nick**: The target suffers 1 strain, "+difficulty_die] * 5 + [
      "**Slowed down**: The target can only act during the last allied initiative slot this turn, "+difficulty_die] * 5 + [
      "**Sudden Jolt**: The target drops whatever is in hand, "+difficulty_die] * 5 + [
      "**Distracted**: The target cannot perform a Free maneuver during his next turn, "+difficulty_die] * 5 + [
      "**Off-Balance**: The target adds "+setback_die+" to his next skill check, "+difficulty_die] * 5 + [
      "**Discouraging Wound**: Flip one light side Destiny point to a dark side Destiny point (reverse if NPC), "+difficulty_die] * 5 + [
      "**Stunned**: The target is staggered until the end of his next turn, "+difficulty_die] * 5 + [
      "**Stinger**: Increase the difficulty of next check by one, "+difficulty_die] * 5 + [
      "**Bowled Over**: The target is knocked prone and suffers 1 strain, "+difficulty_die+difficulty_die] * 5 + [
      "**Head Ringer**: The target increases the difficulty of all Intellect and Cunning checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
      "**Fearsome Wound**: The target increases the difficulty of all Presence and Willpower checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
      "**Agonizing Wound**: The target increases the difficulty of all Brawn and Agility checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
      "**Slightly Dazed**: The target is disoriented until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
      "**Scattered Senses**: The target removes all "+boost_die+" from skill checks until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
      "**Hamstrung**: The target loses his free maneuver until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
      "**Overpowered**: The target leaves himself open, and the attacker may immediately attempt another free attack agains him, using the exact same pool as the original, "+difficulty_die+difficulty_die] * 5 + [
      "**Winded**: Until the end of the encounter, the target cannot voluntarily suffer strain to activate any abilities or gain additional maneuvers, "+difficulty_die+difficulty_die] * 5 + [
      "**Compromised**: Incerase difficulty of all skill checks by one until the end of the encounter, "+difficulty_die+difficulty_die] * 5 + [
      "**At the brink**: The target suffers 1 strain each time he performs an action, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
      "**Crippled**: One of the target's limbs (selected by the GM) is crippled until healed or replaced. Increase difficulty of all checks that require use of that limb by one, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
      "**Maimed**: One of the target's limbs (selected by the GM) is permanently lost. Unless the target has a cybernetic replacement, the target cannot perform actions that would require the use of that limb. All other actions gain "+setback_die+", "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
      "HI"] * 5 + [
      "**Temporarily Lame**: Until this critical injury is healed, the target cannot perform more than one maneuver during his turn, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
      "**Blinded**: The target can no longer see. Upgrade the difficulty of all checks twice. Upgrade the difficulty of perception checks three times, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
      "**Knocked Senseless**: The target is staggered for the remainder of the encounter, "+difficulty_die+difficulty_die+difficulty_die] * 5 + [
      "GI"] * 5 + [
      "**Bleeding Out**: Every round, the target suffers 1 wound and 1 strain at the beginning of his turn. For every five wounds he suffers beyond his wound threshold, he suffers one additional critical injury. (If he suffers this one again, roll again), "+difficulty_die+difficulty_die+difficulty_die+difficulty_die] * 10 + [
      "**The End is Nigh**: The target will die after the last initiative slot during the next round, "+difficulty_die+difficulty_die+difficulty_die+difficulty_die] * 10 + [
      "**Dead**: U B Dead :("]

    if roll >= len(injuries):
      results = injuries[-1]
    else:
      results = injuries[roll]

    if results == "HI":
      characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"])
      results = "**Horrific Injury**: Until this criticil injury is healed, treat the target's "+characteristic+" as if it's one lower, "+difficulty_die+difficulty_die+difficulty_die

    if results == "GI":
      characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"])
      results = "**Gruesome Injury**: The target's "+characteristic+" is permanently one lower, "+difficulty_die+difficulty_die+difficulty_die+difficulty_die

    send_message = "Roll: "+str(roll)+"\nInjury:\n"+results

    message_list = send_message.split("\n")
    await ctx.send(message_list[0])
    if len(message_list) > 1:
      for message_item in message_list[1:]:
        await ctx.channel.send(message_item)

  # Parses the command into something the other functions understand
  async def parse_roll(self, ctx, cmd : str = ""):
    user = f"#{ctx.author.id}"
    cmd = re.sub(' +',' ',cmd.upper()) + " "
    if cmd[0] == " ":
      cmd = cmd[1:]
    cmd = self.bot.star_wars.character.replaceSpaces(string.capwords(cmd))
    commands = cmd.split(" ")
    valid_command = False

    if commands[0] == "":
      roll_parameters = [1,0,3,0,0,0,0]
    else:
      roll_parameters = [0,0,0,0,0,0,0]

    if string.capwords(commands[0]) == "Obligations":
      send_message =  self.obligation_roll()

    elif string.capwords(commands[0]) in skill_data:
      self.bot.log("Oh look! This guy has skills!")
      if self.bot.star_wars.character.userHasChar(user):
        self.bot.log("They have a character. That much we know")
        skill_level = self.bot.star_wars.character.char_data(user,"Skills " + string.capwords(commands[0]))

        if string.capwords(commands[0]) == "Lightsaber":
          self.bot.log("The skill is lightsaber")
          char_level = self.bot.star_wars.character.char_data(user,"Characteristics " + self.bot.star_wars.character.lightsaberChar(user))
        else:
          char_level = self.bot.star_wars.character.char_data(user,"Characteristics " + skill_data[string.capwords(commands[0])])

        ability_dice = abs(char_level-skill_level)
        proficiency_dice = min(skill_level,char_level)

        commands = [str(ability_dice)] + [str(proficiency_dice)] + commands[1:]
        self.bot.log("Converted skill to dice")
        valid_command = True
      else:
        self.bot.log("Okay, no they don't i guess")
        send_message =  "You don't have a user. You can make one with /starwarscharacter"

    elif string.capwords(commands[0]) in ["Ranged","Piloting"]:
      self.bot.log("They fucked up writing the name of a ranged or piloting skill")
      if string.capwords(commands[0]) == "Ranged":
        send_message =  "Did you mean \"Ranged - Heavy\" or \"Ranged - Light\""
      else:
        send_message =  "Did you mean \"Piloting - Planetary\" or \"Piloting - Space\""
    else:
      valid_command = True

    if valid_command:
      self.bot.log("Converting commands to dice")
      for i, command in enumerate(commands):
        if command != "":
          command = command.upper()
          if command[0] == "A":
            roll_parameters[0] = int(command.replace("A",""))
          elif command[0] == "P":
            roll_parameters[1] = int(command.replace("P",""))
          elif command[0] == "D":
            roll_parameters[2] = int(command.replace("D",""))
          elif command[0] == "C":
            roll_parameters[3] = int(command.replace("C",""))
          elif command[0] == "B":
            roll_parameters[4] = int(command.replace("B",""))
          elif command[0] == "S":
            roll_parameters[5] = int(command.replace("S",""))
          elif command[0] == "F":
            roll_parameters[6] = int(command.replace("F",""))
          else:
            roll_parameters[i] = int(command)

      self.bot.log("Rolling "+str(roll_parameters))
      roll_results, dice_results = self.roll(roll_parameters[0],roll_parameters[1],roll_parameters[2],roll_parameters[3],roll_parameters[4],roll_parameters[5],roll_parameters[6])

      simplified = self.simplify(roll_results)

      name = self.bot.star_wars.character.getChar_name(user)

      self.bot.log("Returns results and simplified results")

      if simplified == "":
        send_message =  name + " rolls: " + "\n" + self.dice_result_to_emoji(dice_results) + "\nEverything cancels out!"
      else:
        send_message =  name + " rolls: " + "\n" + self.dice_result_to_emoji(dice_results) + "\n" + self.result_to_emoji(simplified)

    message_list = send_message.split("\n")
    await ctx.send(message_list[0])
    if len(message_list) > 1:
      for message_item in message_list[1:]:
        if message_item == "":
          self.bot.log("Tried to send empty message")
        else:
          await ctx.channel.send(message_item)
