import os
import sys
from pathlib import Path
import json
import demjson3
import chardet


def export_json(target, data):  # Writes a json to a certain directory
    """
    :param target: String
    :param data: Dictionary
    """

    jsonFile = json.dumps(data, ensure_ascii=False, indent=2)
    jsonPath = target
    jsonPath.write_text(jsonFile, encoding='utf-16')
    print("Json file written to " + str(jsonPath))


def import_json(target):  # Goes through a directory, then loads json info into a dict
    """
    :param target: String
    """
    import_file = Path(target)
    if os.path.getsize(target) == 0:
        print("Uplugin file is empty? May not have extracted properly.")
        return {}
    with import_file.open(mode='rb') as input_file:
        my_file = input_file.read()
        my_encode = chardet.detect(my_file)['encoding']
        json_array = demjson3.decode(my_file.decode(my_encode))
        return json_array


if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception("No input provided. Please drag and drop extracted UE4 folder onto program.")
    main_folder = Path(sys.argv[1])
    new_manifest = {"Contents": []}

    uplugins = [x for x in main_folder.glob('**/*.uplugin') if x.is_file()]

    for uplugin in uplugins:
        uplugin_data = {"File": "", "Descriptor": ""}
        trunc_path = os.path.relpath(uplugin, main_folder)
        trunc_path = trunc_path.replace('\\', '/')
        rel_path = os.path.join("../../../", trunc_path)
        print(rel_path)
        uplugin_data["File"] = rel_path
        cur_uplugin_data = import_json(uplugin)
        uplugin_data["Descriptor"] = cur_uplugin_data

        new_manifest["Contents"].append(uplugin_data)

    export_file = Path(main_folder.parent, "new.upluginmanifest")
    export_json(export_file, new_manifest)
    input("Export complete! Press enter to exit. ")