import subprocess, os, sys
from datetime import datetime

config = {'manual': False,'info_level': 0, 'restricted_extensions': [], 'ignore_files': ["meta.xml", "meta-generated.xml"], 'author': "Default", 'cache': False, 'sort_type': 1}
type_cases = {'client':["client"], 'server':["server"]}
prefix_cases = {'client':["c_"], 'server':["s_"]}

def get_type(file_path, name):
    if config['manual']:
        input_type = input("Choose type for " + file_path + os.sep + name)
        for type in type_cases:
            if input_type.find(type) >= 0:
                return type
    else:
        name = name.lower()
        for type in type_cases:
            for base_case in type_cases[type]: #check is file name contains cases listed in dictionary above
                if name.find(base_case) >= 0:
                    return type
            for base_case in prefix_cases[type]:
                if name.startswith(base_case):
                    return type

        folders = [folder.lower() for folder in file_path.split("\\")]
        for folder in folders:
            for type in type_cases:
                if folder.find(type) >= 0: #same check, but for folders
                    return type
            for base_case in prefix_cases[type]:
                if name.startswith(base_case):
                    return type

    if config['info_level'] < 3:
        print("WARNING: Can't determine file type!")
    return "shared"

if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]):
    working_folder = sys.argv[1]
    if working_folder == ".":
        working_folder = os.path.dirname(os.path.realpath(__file__))
    
    os.chdir(working_folder)
    with open("meta-generated.xml", "w+") as meta_file:
        meta_file.truncate(0) 
        meta_file.write("<meta>" + "\n")

        name = os.path.basename(working_folder)
        meta_file.write("\t" + "<info name=\"" + name +"\" description=\"Generated by MTA-Resource-Tool\" author=\"" + config['author'] + "\"/>" + "\n")
        
        for root, dirs, files in os.walk(working_folder):
            files[:] = [f for f in files if not f in config['ignore_files']]
            folders = root.split("\\")
            if not folders[-1].startswith('.'): #ignoring .git and etc. basically
                meta_file.write("\n")

                for file in files:
                    file_path = os.path.join(root, file)
                    file_path = file_path.replace(working_folder + os.sep, "")

                    name, ext = os.path.splitext(file)
                    if ext == ".lua" or ext == ".luac":
                        type = get_type(file_path, name)
                        if config['info_level'] == 0:
                            print("INFO:", file_path, "will be written as", type, "file")

                        if type == "client" and config['cache'] == False:
                            post_addition = 'cache = "false"' 
                        else:
                            post_addition = ""

                        meta_row = "\t" + "<script src=\"" + file_path + "\" type=\"" + type + "\" " + post_addition +"/>" + "\n"
                        meta_file.write(meta_row)


                    elif not ext in config['restricted_extensions']:
                        if config['info_level'] == 0:
                            print("INFO:", file_path, "will be written")

                        meta_row = "\t" + "<file src=\"" + file_path + "\"/>" + "\n"
                        meta_file.write(meta_row)
                    else:
                        if config['info_level'] == 0:
                            print("INFO:", file_path, "has restricted extensions")

        meta_file.write("</meta>")
else:
    sys.exit("ERROR: No file or directory specified!")