import random
import re
import string
import json
import os

from . import swchar
from funcs import logThis

with open("resources/swskills.json", "r") as f:
    skillData = json.load(f)

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

    for x in range(prof):
        choice = random.choice(["","S","S","SS","SS","A","SA","SA","SA","AA","AA","R"])
        result += choice
        diceResult.append("prof"+choice)
    
    for x in range(dif):
        choice = random.choice(["","F","FF","H","H","H","HH","FH"]) 
        result += choice
        diceResult.append("dif"+choice)

    for x in range(cha):
        choice = random.choice(["","F","F","FF","FF","H","H","FH","FH","HH","HH","D"])
        result += choice
        diceResult.append("cha"+choice)
    
    for x in range(boo):
        choice = random.choice(["","","S","SA","AA","A"])
        result += choice
        diceResult.append("boo"+choice)

    for x in range(setb):
        choice = random.choice(["","","F","F","H","H"])
        result += choice
        diceResult.append("setb"+choice)
    
    for x in range (force):
        choice = random.choice(["B","B","B","B","B","B","BB","L","L","LL","LL","LL"])
        result += choice
        diceResult.append("force"+choice)

    return result, diceResult

# Lets dice cancel each other out
def simplify(result : str):
    logThis("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 x in range(success):
            simp += "S"
    elif success < 0:
        for x in range(abs(success)):
            simp += "F"
    
    if advantage > 0:
        for x in range(advantage):
            simp += "A"
    elif advantage < 0:
        for x in range(abs(advantage)):
            simp += "H"
    
    simp += result

    return simp

# Returns emoji that symbolize the dice results
def diceResultToEmoji(diceResults : list):
    emoji = ""
    for result in diceResults:
        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 resultToEmoji(result : str):
    emoji = ""
    for char in result:
        if char == 'S':
            emoji += "<:success:690971244971163718> "
        elif char == 'A':
            emoji += "<:advantage:690970761611051079> "
        elif char == 'R':
            emoji += "<:swtriumph:690971267486187643> "
        elif char == 'F':
            emoji += "<:failure:690970957786906664> "
        elif char == 'H':
            emoji += "<:threat:690971009469382656> "
        elif char == 'D':
            emoji += "<:despair:690971200163414238> "
        elif char == 'L':
            emoji += "<:light:691010089905029171>"
        elif char == 'B':
            emoji += "<:dark:691010101901000852>"
    
    return emoji

# Converts emoji into letters
def emojiToResult(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 diceToEmoji(dice : list):
    emoji = ""

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

    return emoji

# Rolls for obligation
def obligationRoll():
    logThis("Rolling for obligation")
    with open("resources/swcharacters.json", "r") as f:
        data = json.load(f)
    
    table = []

    for character in data:
        for obligation in data[character]["Obligations"]:
            for x 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
def critRoll(addington : int):
    dd = "<:difficulty:690973992470708296>"
    sd = "<:setback:690972157890658415>"
    bd = "<:boost:690972178216386561>"
    roll = random.randint(1,100) + addington
    injuries = [
        "**Minor nick**: The target suffers 1 strain, "+dd] * 5 + [
        "**Slowed down**: The target can only act during the last allied initiative slot this turn, "+dd] * 5 + [
        "**Sudden Jolt**: The target drops whatever is in hand, "+dd] * 5 + [
        "**Distracted**: The target cannot perform a Free maneuver during his next turn, "+dd] * 5 + [
        "**Off-Balance**: The target adds "+sd+" to his next skill check, "+dd] * 5 + [
        "**Discouraging Wound**: Flip one light side Destiny point to a dark side Destiny point (reverse if NPC), "+dd] * 5 + [
        "**Stunned**: The target is staggered until the end of his next turn, "+dd] * 5 + [
        "**Stinger**: Increase the difficulty of next check by one, "+dd] * 5 + [
        "**Bowled Over**: The target is knocked prone and suffers 1 sttrain, "+dd+dd] * 5 + [
        "**Head Ringer**: The target increases the difficulty of all Intellect and Cunning checks by one until the end of the encounter, "+dd+dd] * 5 + [
        "**Fearsome Wound**: The target increases the difficulty of all Presence and Willpower checks by one until the end of the encounter, "+dd+dd] * 5 + [
        "**Agonizing Wound**: The target increases the difficulty of all Brawn and Agility checks by one until the end of the encounter, "+dd+dd] * 5 + [
        "**Slightly Dazed**: The target is disoriented until the end of the encounter, "+dd+dd] * 5 + [
        "**Scattered Senses**: The target removes all "+bd+" from skill checks until the end of the encounter, "+dd+dd] * 5 + [
        "**Hamstrung**: The target loses his free maneuver until the end of the encounter, "+dd+dd] * 5 + [
        "**Overpowered**: The target leaves himselp open, and the attacker may immediately attempt another free attack agains him, using the exact same pool as the original, "+dd+dd] * 5 + [
        "**Winded**: Until the end of the encounter, the target cannot voluntarily suffer strain to activate any abilities or gain additional maneuvers, "+dd+dd] * 5 + [
        "**Compromised**: Incerase difficulty of all skill checks by one until the end of the encounter, "+dd+dd] * 5 + [
        "**At the brink**: The target suffers 1 strain each time he performs an action, "+dd+dd+dd] * 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, "+dd+dd+dd] * 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 "+sd+", "+dd+dd+dd] * 5 + [
        "HI"] * 5 + [
        "**Temporarily Lame**: Until this critical injury is healed, the target cannot perform more than one maneuver during his turn, "+dd+dd+dd] * 5 + [
        "**Blinded**: The target can no longer see. Upgrade the difficulty of all checks twice. Upgrade the difficulty of perception checks three times, "+dd+dd+dd] * 5 + [
        "**Knocked Senseless**: The target is staggered for the remainder of the encounter, "+dd+dd+dd] * 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), "+dd+dd+dd+dd] * 10 + [
        "**The End is Nigh**: The target will die after the last initiative slot during the next round, "+dd+dd+dd+dd] * 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, "+dd+dd+dd
    
    if results == "GI":
        characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"])
        results = "**Gruesome Injury**: The target's "+characteristic+" is permanently one lower, "+dd+dd+dd+dd

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

# Parses the command into something the other functions understand
def parseRoll(user : str,cmd : str = ""):
    cmd = re.sub(' +',' ',cmd.upper()) + " "
    if cmd[0] == " ":
        cmd = cmd[1:]
    cmd = swchar.replaceSpaces(string.capwords(cmd))
    commands = cmd.split(" ")
    if commands[0] == "":
        rollParameters = [1,0,3,0,0,0,0]
    else:
        rollParameters = [0,0,0,0,0,0,0]

    if string.capwords(commands[0]) == "Obligations":
        return obligationRoll()
    
    elif string.capwords(commands[0]) in skillData:
        logThis("Oh look! This guy has skills!")
        if swchar.userHasChar:
            logThis("They have a character. That much we know")
            skillLevel = swchar.charData(user,"Skills " + string.capwords(commands[0]))

            if string.capwords(commands[0]) == "Lightsaber":
                logThis("The skill is lightsaber")
                charLevel = swchar.charData(user,"Characteristics " + swchar.lightsaberChar(user))
            else:
                charLevel = swchar.charData(user,"Characteristics " + skillData[string.capwords(commands[0])])

            abilityDice = abs(charLevel-skillLevel)
            proficiencyDice = min(skillLevel,charLevel)

            commands = [str(abilityDice)] + [str(proficiencyDice)] + commands[1:]
            logThis("Converted skill to dice")
        else:
            logThis("Okay, no they don't i guess")
            return "You don't have a user. You can make one with !swchar"

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

    try:
        logThis("Converting commands to dice")
        for x in range(len(commands)):
            if commands[x] != "":
                commands[x] = commands[x].upper()
                if commands[x][0] == "A":
                    rollParameters[0] = int(commands[x].replace("A",""))
                elif commands[x][0] == "P":
                    rollParameters[1] = int(commands[x].replace("P",""))
                elif commands[x][0] == "D":
                    rollParameters[2] = int(commands[x].replace("D",""))
                elif commands[x][0] == "C":
                    rollParameters[3] = int(commands[x].replace("C",""))
                elif commands[x][0] == "B":
                    rollParameters[4] = int(commands[x].replace("B",""))
                elif commands[x][0] == "S":
                    rollParameters[5] = int(commands[x].replace("S",""))
                elif commands[x][0] == "F":
                    rollParameters[6] = int(commands[x].replace("F",""))
                else:
                    rollParameters[x] = int(commands[x])
    except:
        logThis("Someone fucked u-up! (it was them)")
        return "Invalid input!"
    
    logThis("Rolling "+str(rollParameters))
    rollResults, diceResults = roll(rollParameters[0],rollParameters[1],rollParameters[2],rollParameters[3],rollParameters[4],rollParameters[5],rollParameters[6])
    
    simplified = simplify(rollResults)

    name = swchar.getName(user)
    
    logThis("Returns results and simplified results")

    if simplified == "":
        return name + " rolls: " + "\n" + diceResultToEmoji(diceResults) + "\nEverything cancels out!"
    else:
        return name + " rolls: " + "\n" + diceResultToEmoji(diceResults) + "\n" + resultToEmoji(simplified)
      
