#!/usr/bin/env python3
import json
import string
import random
import glob, os
import sys

used_names = []


# rand string for class names
def gen_rand_str():
    rand_str = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=8))
    while rand_str in used_names:
        rand_str = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=8))

    used_names.append(rand_str)
    return rand_str + str(random.randint(0, 1000))


def get_rand_code(isInFunc):
    indentasi = random.randint(0, 5);
    indentasiStr = ""
    for num in range(0, indentasi):
        indentasiStr += "\t"

    # 随机缩进
    num = random.randint(0, 4);
    code = ";\n"
    filed_name = gen_rand_str()
    filed_value = random.randint(0, 100000);
    # 随机代码
    if num == 0:
        code += indentasiStr + "String " + filed_name + "=\"" + gen_rand_str() + "\";\n"
    elif num == 1:
        code += indentasiStr + "int " + filed_name + "=" + str(filed_value) + ";\n"
    elif num == 2:
        code += indentasiStr + "float " + filed_name + "=" + str(filed_value) + ";\n"
    elif num == 3:
        code += indentasiStr + "double " + filed_name + "=" + str(filed_value) + ";\n"
    elif num == 4:
        code += indentasiStr + "long " + filed_name + "=" + str(filed_value) + ";\n"

    if isInFunc:
        if num == 0:
            code += "if(\"" + filed_name + "\".equals(\"" + gen_rand_str() + "\")){}//interference code\n"
        else:
            if random.randint(0, 10) % 2 == 0:
                code += "while(" + filed_name + "++<" + str(filed_value) + "+1){}\n"
            else:
                index = gen_rand_str()
                code += "for(int " + index + "="+str(filed_value+1)+";"+index+"<"+filed_name+";"+index+"++){}//interference code\n"

    return code


def get_brackets(line):
    left = line.count("{")
    right = line.count("}")
    return left - right


def is_note(line):
    final_line = line.replace("://", "")
    return "//" in final_line or "\t*" in final_line


def process_file_content(path, file_name):
    # print("processing content: %s..." % path)
    with open(path, "r", encoding="utf-8") as f:
        # readlines以列表的形式将文件读出
        lines = f.readlines()
    if "***Keep***" in lines[0]:
        return

    with open(path, "w", encoding="utf-8") as f_w:
        isReturn = False
        isErrorIf = False
        return_level = 0
        func_level = 0
        isAbstract = False
        for line in lines:
            # 接口和抽象类 直接跳过
            if "interface" in line or "abstract" in line:
                isAbstract = True
            if isAbstract or is_note(line):
                f_w.write(line)
                continue

            # 没加{}的if else
            if ("if(" in line or "if (" in line) and "{" not in line:
                isErrorIf = True
            # return后有多行代码
            if "return" in line or ("throw" in line and not isReturn):
                isReturn = True
                return_level = get_brackets(line)

            if isReturn:
                return_level += get_brackets(line)
                if return_level < 0:
                    return_level = 0

            if " class " in line and "{" in line:
                func_level = 0

            if ("){\n" in line or ") {\n" in line) and func_level == 0 and not isReturn:
                func_level = get_brackets(line)
            elif func_level != 0:
                if "new " in line and "{" in line:
                    func_level = 0
                else:
                    func_level += get_brackets(line)
                    if func_level < 0:
                        func_level = 0

            # 需要忽略的行
            if not isReturn and not isErrorIf and \
                    ";\n" in line and \
                    "return" not in line and \
                    "break" not in line and \
                    "continue" not in line and \
                    "import" not in line and \
                    "package" not in line and \
                    "throw" not in line and \
                    "};" not in line and \
                    "});" not in line and \
                    not is_note(line):

                if random.randint(0, 20) % 2 == 0:
                    line = line.replace(";\n", get_rand_code(func_level > 0))

            if ";" in line:
                isErrorIf = False

            if ";\n" in line and return_level == 0:
                isReturn = False

            f_w.write(line)
        # print("done\n")
    return


# perform content replace for the files
for root, dirs, files in os.walk("../../../app/src/main"):
    directory = os.path.join(os.getcwd(), root)
    for file in files:
        if file.endswith(".java"):
            # get the path of the java file
            path = os.path.join(directory, file)

            process_file_content(path, file)

for root, dirs, files in os.walk("../../../lib_base/src/main"):
    directory = os.path.join(os.getcwd(), root)
    for file in files:
        if file.endswith(".java"):
            # get the path of the java file
            path = os.path.join(directory, file)

            process_file_content(path, file)

print("processing file content done")
