######################################
# EASY THAUMCRAFT RESEARCH GENERATOR #
######################################
import os
import json
import copy 
import re
# Made to remove duplicate contents for Thaumcraft researches.
################################################################################
################################################################################
# CHANGE THIS PART !! AND NOWHERE ELSE #########################################
################################################################################
DIR_SRC = 'data/' # directory for your source jsons.
DIR_DEST = '../src/main/resources/assets/planarartifice/research/' # where should it put the resulted jsons?
DIR_LANG = 'res/' # where should it put the language boilerplate?
CONFIG_TEST_MODE = False # if this is set to true, DIR_DEST and DIR_LANG is ignored and is both set to 'res/'.
CONFIG_AUTO_ATTACH_MODID_IN_RECIPES = True # whether to auto-attach mod id in "recipes" key.
################################################################################
# CHANGE THIS PART !! AND NOWHERE ELSE #########################################
################################################################################
################################################################################
keys = []
modid = ""
# FUNCTIONS
def capAll(n):
    return n.upper()

def hasExclamation(n):
    return n[0] == '!'

def recipefy(n):
    if hasExclamation(n):
        n = n[1:]
    if CONFIG_AUTO_ATTACH_MODID_IN_RECIPES:
        if (":" in n):
            return n
        return modid + ":" + n
    else:
        return n

def itemify(n):
    if re.search(r'enchant:\d+;\d+', n):
        l = n[8:].split(";")
        return "thaumcraft:enchanted_placeholder;1;0;{ench:[{id:" + l[0] + "s,lvl:" + l[1] + "s}]}"
    if re.search(r'crystal:\w+', n):
        return "thaumcraft:crystal_essence;1;0;{Aspects:[{amount:1,key:\"" + n[8:] + "\"}]}"
    if re.search(r'phial:\w+', n):
        return "thaumcraft:phial;1;1;{Aspects:[{amount:10,key:\"" + n[6:] + "\"}]}"
    return n

def getTitle(n):
    n = n.split(".")[2]
    return n.replace("_", " ").title()

if CONFIG_TEST_MODE:
    print("Detected Test Mode. Changing Target Directory...")
    DIR_DEST = 'res/'
    DIR_LANG = 'res/'
print("Starting Conversion...")
for filename in os.listdir(DIR_SRC):
    # READING SOURCE FILE
    f = open(DIR_SRC + filename, "r")
    src = json.load(f)
    f.close()
    print("Loaded json " + filename)
    dest = dict()
    dest["_comment"] = "THIS JSON IS AUTOMATICALLY GENERATED BY ETRGv1 for TC6. DO NOT EDIT THIS JSON. EDIT THE SOURCE JSON INSTEAD."
    dest["entries"] = []

    # READING FILE-SCOPE VARIABLES
    modid = src["modid"]
    category = src["category"]
    if "tc.research_category." + category not in keys:
        keys.append("tc.research_category." + category)
    prefix = ""
    if "prefix" in src:
        prefix = src["prefix"]

    # ITERATING THROUGH ENTRIES
    for srcEnt in src["entries"]:
        # CARRYING OVER STUFF
        destEnt = dict()
        if srcEnt["key"][0] == '!':
            destEnt["key"] = srcEnt["key"]
        else:
            destEnt["key"] = prefix + srcEnt["key"]
        keyLoc = srcEnt["key"].replace("!", "").lower()
        destEnt["name"] = modid + ".research." + keyLoc + ".title"
        destEnt["category"] = category
        if destEnt["name"] not in keys:
            keys.append(destEnt["name"])
        if "icons" in srcEnt:
            destEnt["icons"] = srcEnt["icons"]
        if "parents" in srcEnt:
            destEnt["parents"] = srcEnt["parents"]
        if "meta" in srcEnt:
            destEnt["meta"] = list(map(capAll, srcEnt["meta"]))
        if "location" in srcEnt:
            destEnt["location"] = srcEnt["location"]
        dest["entries"].append(destEnt)
        # rewards
        if "rewards" in srcEnt:
            rewardItem = []
            rewardKnowledge = []
            for srcReward in srcEnt["rewards"]:
                if srcReward.startswith("OBSERVATION;") or srcReward.startswith("THEORY;"):
                    rewardKnowledge.append(srcReward)
                else:
                    rewardItem.append(srcReward)
            if len(rewardItem) != 0:
                destEnt["reward_item"] = rewardItem
            if len(rewardKnowledge) != 0:
                destEnt["reward_knowledge"] = rewardKnowledge

        # STAGES / ADDENDA
        destEnt["stages"] = []
        recipes = []
        for i, srcStage in enumerate(srcEnt["stages"]):
            destStage = dict()
            if i is len(srcEnt["stages"]) - 1:
                destStage["text"] = modid + ".research." + keyLoc + ".complete.text"
            else:
                destStage["text"] = modid + ".research." + keyLoc + ".stage." + str(i + 1) + ".text"
            if destStage["text"] not in keys:
                keys.append(destStage["text"])
            if "items" in srcStage:
                destStage["required_item"] = list(map(itemify, srcStage["items"]))
            if "crafts" in srcStage:
                destStage["required_craft"] = list(map(itemify, srcStage["crafts"]))
            if "knowledges" in srcStage:
                destStage["required_knowledge"] = srcStage["knowledges"]
            if "researches" in srcStage:
                destStage["required_research"] = srcStage["researches"]
            if "recipes" in srcStage:
                recipes.extend(list(map(recipefy, srcStage["recipes"])))
                destStage["recipes"] = copy.copy(recipes)
                alsoRequired = list(filter(hasExclamation, srcStage["recipes"]))
                if len(alsoRequired) != 0:
                    if "required_craft" not in destStage:
                        destStage["required_craft"] = []
                    destStage["required_craft"].extend(list(map(recipefy, alsoRequired)))
            elif len(recipes) != 0:
                destStage["recipes"] = recipes
            if "warp" in srcStage:
                destStage["warp"] = srcStage["warp"]
            destEnt["stages"].append(destStage)
        
        if "addenda" in srcEnt:
            destEnt["addenda"] = []
            for i, srcAddendum in enumerate(srcEnt["addenda"]):
                destAddendum = dict()
                destAddendum["text"] = modid + ".research." + keyLoc + ".addendum." + str(i + 1) + ".text"
                if destAddendum["text"] not in keys:
                    keys.append(destAddendum["text"])
                if "recipes" in srcAddendum:
                    recipes.extend(list(map(recipefy, srcAddendum["recipes"])))
                    destAddendum["recipes"] = copy.copy(recipes)
                if "parents" in srcAddendum:
                    destAddendum["required_research"] = srcAddendum["parents"]
                destEnt["addenda"].append(destAddendum)

    # WRITING TO DESTINATION FILE
    f = open(DIR_DEST + filename, "w")
    f.write(json.dumps(dest, indent=2))
    f.close()

# CREATING LANGUAGE BOILERPLATE
f = open(DIR_LANG + "boilerplate.lang", "w")
f.write("# ---   ----   --- #\n")
f.write("# --- Research --- #\n")
f.write("# ---   ----   --- #\n")
for key in keys:
    if key.endswith(".title"):
        f.write("# " + getTitle(key) + "\n")
    f.write(key + "=\n")
f.write("# --- End of Research --- #\n")
f.close()

print("Finished Conversion.")
# prodzpod 2020
######################################
# EASY THAUMCRAFT RESEARCH GENERATOR #
######################################
import os
import json
import copy 
import re
# Made to remove duplicate contents for Thaumcraft researches.
################################################################################
################################################################################
# CHANGE THIS PART !! AND NOWHERE ELSE #########################################
################################################################################
DIR_SRC = 'data/' # directory for your source jsons.
DIR_DEST = '../src/main/resources/assets/planarartifice/research/' # where should it put the resulted jsons?
DIR_LANG = 'res/' # where should it put the language boilerplate?
CONFIG_TEST_MODE = False # if this is set to true, DIR_DEST and DIR_LANG is ignored and is both set to 'res/'.
CONFIG_AUTO_ATTACH_MODID_IN_RECIPES = True # whether to auto-attach mod id in "recipes" key.
################################################################################
# CHANGE THIS PART !! AND NOWHERE ELSE #########################################
################################################################################
################################################################################
keys = []
modid = ""
# FUNCTIONS
def capAll(n):
    return n.upper()

def hasExclamation(n):
    return n[0] == '!'

def recipefy(n):
    if hasExclamation(n):
        n = n[1:]
    if CONFIG_AUTO_ATTACH_MODID_IN_RECIPES:
        if (":" in n):
            return n
        return modid + ":" + n
    else:
        return n

def itemify(n):
    if re.search(r'enchant:\d+;\d+', n):
        l = n[8:].split(";")
        return "thaumcraft:enchanted_placeholder;1;0;{ench:[{id:" + l[0] + "s,lvl:" + l[1] + "s}]}"
    if re.search(r'crystal:\w+', n):
        return "thaumcraft:crystal_essence;1;0;{Aspects:[{amount:1,key:\"" + n[8:] + "\"}]}"
    if re.search(r'phial:\w+', n):
        return "thaumcraft:phial;1;1;{Aspects:[{amount:10,key:\"" + n[6:] + "\"}]}"
    return n

def getTitle(n):
    n = n.split(".")[2]
    return n.replace("_", " ").title()

if CONFIG_TEST_MODE:
    print("Detected Test Mode. Changing Target Directory...")
    DIR_DEST = 'res/'
    DIR_LANG = 'res/'
print("Starting Conversion...")
for filename in os.listdir(DIR_SRC):
    # READING SOURCE FILE
    f = open(DIR_SRC + filename, "r")
    src = json.load(f)
    f.close()
    print("Loaded json " + filename)
    dest = dict()
    dest["_comment"] = "THIS JSON IS AUTOMATICALLY GENERATED BY ETRGv1 for TC6. DO NOT EDIT THIS JSON. EDIT THE SOURCE JSON INSTEAD."
    dest["entries"] = []

    # READING FILE-SCOPE VARIABLES
    modid = src["modid"]
    category = src["category"]
    if "tc.research_category." + category not in keys:
        keys.append("tc.research_category." + category)
    prefix = ""
    if "prefix" in src:
        prefix = src["prefix"]

    # ITERATING THROUGH ENTRIES
    for srcEnt in src["entries"]:
        # CARRYING OVER STUFF
        destEnt = dict()
        if srcEnt["key"][0] == '!':
            destEnt["key"] = srcEnt["key"]
        else:
            destEnt["key"] = prefix + srcEnt["key"]
        keyLoc = srcEnt["key"].replace("!", "").lower()
        destEnt["name"] = modid + ".research." + keyLoc + ".title"
        destEnt["category"] = category
        if destEnt["name"] not in keys:
            keys.append(destEnt["name"])
        if "icons" in srcEnt:
            destEnt["icons"] = srcEnt["icons"]
        if "parents" in srcEnt:
            destEnt["parents"] = srcEnt["parents"]
        if "meta" in srcEnt:
            destEnt["meta"] = list(map(capAll, srcEnt["meta"]))
        if "location" in srcEnt:
            destEnt["location"] = srcEnt["location"]
        dest["entries"].append(destEnt)
        # rewards
        if "rewards" in srcEnt:
            rewardItem = []
            rewardKnowledge = []
            for srcReward in srcEnt["rewards"]:
                if srcReward.startswith("OBSERVATION;") or srcReward.startswith("THEORY;"):
                    rewardKnowledge.append(srcReward)
                else:
                    rewardItem.append(srcReward)
            if len(rewardItem) != 0:
                destEnt["reward_item"] = rewardItem
            if len(rewardKnowledge) != 0:
                destEnt["reward_knowledge"] = rewardKnowledge

        # STAGES / ADDENDA
        destEnt["stages"] = []
        recipes = []
        for i, srcStage in enumerate(srcEnt["stages"]):
            destStage = dict()
            if i is len(srcEnt["stages"]) - 1:
                destStage["text"] = modid + ".research." + keyLoc + ".complete.text"
            else:
                destStage["text"] = modid + ".research." + keyLoc + ".stage." + str(i + 1) + ".text"
            if destStage["text"] not in keys:
                keys.append(destStage["text"])
            if "items" in srcStage:
                destStage["required_item"] = list(map(itemify, srcStage["items"]))
            if "crafts" in srcStage:
                destStage["required_craft"] = list(map(itemify, srcStage["crafts"]))
            if "knowledges" in srcStage:
                destStage["required_knowledge"] = srcStage["knowledges"]
            if "researches" in srcStage:
                destStage["required_research"] = srcStage["researches"]
            if "recipes" in srcStage:
                recipes.extend(list(map(recipefy, srcStage["recipes"])))
                destStage["recipes"] = copy.copy(recipes)
                alsoRequired = list(filter(hasExclamation, srcStage["recipes"]))
                if len(alsoRequired) != 0:
                    if "required_craft" not in destStage:
                        destStage["required_craft"] = []
                    destStage["required_craft"].extend(list(map(recipefy, alsoRequired)))
            elif len(recipes) != 0:
                destStage["recipes"] = recipes
            if "warp" in srcStage:
                destStage["warp"] = srcStage["warp"]
            destEnt["stages"].append(destStage)
        
        if "addenda" in srcEnt:
            destEnt["addenda"] = []
            for i, srcAddendum in enumerate(srcEnt["addenda"]):
                destAddendum = dict()
                destAddendum["text"] = modid + ".research." + keyLoc + ".addendum." + str(i + 1) + ".text"
                if destAddendum["text"] not in keys:
                    keys.append(destAddendum["text"])
                if "recipes" in srcAddendum:
                    recipes.extend(list(map(recipefy, srcAddendum["recipes"])))
                    destAddendum["recipes"] = copy.copy(recipes)
                if "parents" in srcAddendum:
                    destAddendum["required_research"] = srcAddendum["parents"]
                destEnt["addenda"].append(destAddendum)

    # WRITING TO DESTINATION FILE
    f = open(DIR_DEST + filename, "w")
    f.write(json.dumps(dest, indent=2))
    f.close()

# CREATING LANGUAGE BOILERPLATE
f = open(DIR_LANG + "boilerplate.lang", "w")
f.write("# ---   ----   --- #\n")
f.write("# --- Research --- #\n")
f.write("# ---   ----   --- #\n")
for key in keys:
    if key.endswith(".title"):
        f.write("# " + getTitle(key) + "\n")
    f.write(key + "=\n")
f.write("# --- End of Research --- #\n")
f.close()

print("Finished Conversion.")
# prodzpod 2020
###################################### # EASY THAUMCRAFT RESEARCH GENERATOR # ###################################### # Made to remove duplicate contents for Thaumcraft researches. ################################################################################ ################################################################################ # CHANGE THIS PART !! AND NOWHERE ELSE ######################################### ################################################################################ # directory for your source jsons. # where should it put the resulted jsons? # where should it put the language boilerplate? # if this is set to true, DIR_DEST and DIR_LANG is ignored and is both set to 'res/'. # whether to auto-attach mod id in "recipes" key. ################################################################################ # CHANGE THIS PART !! AND NOWHERE ELSE ######################################### ################################################################################ ################################################################################ # FUNCTIONS # READING SOURCE FILE # READING FILE-SCOPE VARIABLES # ITERATING THROUGH ENTRIES # CARRYING OVER STUFF # rewards # STAGES / ADDENDA # WRITING TO DESTINATION FILE # CREATING LANGUAGE BOILERPLATE #\n") #\n") #\n") #\n") # prodzpod 2020