import math
#import discord
import json

from funcs import cap, logThis

# Calculates D&D stat modifier
def modifier(statistic):
    mods = math.floor((statistic-10)/2)
    if mods >= 0:
        mods = "+"+str(mods)
    return(str(mods))

saves = ["strength_save","dexterity_save","constitution_save","intelligence_save","wisdom_save","charisma_save"]
abilities = ["acrobatics","animal_handling","arcana","athletics","deception","history","insight","intimidation","investigation","medicine","nature","perception","performance","persuasion","religion","sleight_of_hand","stealth","survival"]

# Looks up a monster
def monsterFunc(command):
    logThis("Looking up "+command)

    # 1-letter monsters don't exist
    if len(command) < 2:
        logThis("Monster name too short (error code 601)")
        return("I don't know that monster... (error code 601)","","","","","")
    else:
        # Opens "mensters.json"
        data = json.load(open('resources/lookup/monsters.json', encoding = "utf8"))
        for monster in data:
            if "name" in monster and str(command) == monster["name"]:
                logThis("Found it!")

                # Looks at the information about the monster and returns that information
                # in seperate variables, allowing Gwendolyn to know where to seperate
                # the messages
                if monster["subtype"] != "":
                    typs = (monster["type"]+" ("+monster["subtype"]+")")
                else:
                    typs = monster["type"]
                con_mod = math.floor((monster["constitution"]-10)/2)
                hit_dice = monster["hit_dice"]

                stats = ("**Str:** "+str(monster["strength"])+" ("+modifier(monster["strength"])+")\t**Dex:** "+str(monster["dexterity"])+" ("+modifier(monster["dexterity"])+")\t**Con:** "+str(monster["constitution"])+" ("+modifier(monster["constitution"])+")\n**Int: **"+str(monster["intelligence"])+" ("+modifier(monster["intelligence"])+")\t**Wis: **"+str(monster["wisdom"])+" ("+modifier(monster["wisdom"])+")\t**Cha: **"+str(monster["charisma"])+" ("+modifier(monster["charisma"])+")")

                saving_throws = ""
                for save in saves:
                    if save in monster:
                        if monster[save] >= 0:
                            saving_throws += " "+cap(save[:3])+" +"+str(monster[save])+","
                        else:
                            saving_throws += " "+cap(save[:3])+" "+str(monster[save])+","
                if saving_throws != "":
                    saving_throws = "\n**Saving Throws**"+saving_throws[:-1]

                skills = ""
                for skill in abilities:
                    if skill in monster:
                        if monster[skill] >= 0:
                            skills += " "+cap(skill.replace("_"," "))+" +"+str(monster[skill])+","
                        else:
                            skills += " "+cap(skill.replace("_"," "))+" "+str(monster[skill])+","
                if skills != "":
                    skills = "\n**Skills**"+skills[:-1]

                vulnerabilities = monster["damage_vulnerabilities"]
                if vulnerabilities != "":
                    vulnerabilities = "\n**Damage Vulnerabilities** "+vulnerabilities

                resistances = monster["damage_resistances"]
                if resistances != "":
                    resistances = "\n**Damage Resistances** "+resistances

                immunities = monster["damage_immunities"]
                if immunities != "":
                    immunities = "\n**Damage Immunities** "+immunities

                c_immunities = monster["condition_immunities"]
                if c_immunities != "":
                    c_immunities = "\n**Condition Immunities** "+c_immunities

                spec_ab = ""
                if "special_abilities" in monster:
                    for ability in monster["special_abilities"]:
                        spec_ab += "\n\n***"+ability["name"]+".*** "+ability["desc"]

                act = ""
                if "actions" in monster:
                    for action in monster["actions"]:
                        act += "\n\n***"+action["name"]+".*** "+action["desc"]

                react = ""
                if "reactions" in monster:
                    for reaction in monster["reactions"]:
                        react += "\n\n***"+reaction["name"]+".*** "+reaction["desc"]

                leg_act = ""
                if "legendary_actions" in monster:
                    for action in monster["legendary_actions"]:
                        leg_act += "\n\n***"+action["name"]+".*** "+action["desc"]

                if con_mod < 0:
                    hit_dice += (" - "+str(con_mod * int(monster["hit_dice"].replace("d"," ").split()[0])*(-1)))
                if con_mod > 0:
                    hit_dice += (" + "+str(con_mod * int(monster["hit_dice"].replace("d"," ").split()[0])))
                    
                new_part = "\n--------------------"

                monster_type = monster["size"]+" "+typs+", "+monster["alignment"]+"*"

                basic_info = "\n**Armor Class** "+str(monster["armor_class"])+"\n**Hit Points** "+str(monster["hit_points"])+" ("+hit_dice+")\n**Speed **"+monster["speed"]+new_part+"\n"

                text1 = (monster_type+new_part+basic_info+stats+new_part+saving_throws+skills+vulnerabilities+resistances+immunities+c_immunities+"\n**Senses** "+monster["senses"]+"\n**Languages** "+monster["languages"]+"\n**Challenge** "+monster["challenge_rating"])

                text2 = (spec_ab)
                text3 = (act)
                text4 = (react)
                text5 = (leg_act)

                logThis("Returning monster information")
                return(str(command),text1,text2,text3,text4,text5)
        logThis("Monster not in database (error code 602)")
        return("I don't know that monster... (error code 602)","","","","","")

# Looks up a spell
def spellFunc(command):
    logThis("Looking up "+command)

    # Opens "spells.json"
    data = json.load(open('resources/lookup/spells.json', encoding = "utf8"))
    if str(command) in data:
        logThis("Returning spell information")
        spell_output = ("***"+str(command)+"***\n*"+str(data[str(command)]["level"])+" level "+str(data[str(command)]["school"])+"\nCasting Time: "+str(data[str(command)]["casting_time"])+"\nRange: "+str(data[str(command)]["range"])+"\nComponents: "+str(data[str(command)]["components"])+"\nDuration: "+str(data[str(command)]["duration"])+"*\n \n"+str(data[str(command)]["description"]))
    else:
        logThis("I don't know that spell (error code 501)")
        spell_output = "I don't think that's a spell (error code 501)"
    logThis("Successfully ran !spell")
    return(spell_output)
