# -*-coding:utf-8-*-
import random
import re
import os

class JavaGarble:
    __used_names = []
    __variables = []
    __functions = []

    def __gen_rand_str(self):
        result = ""
        while len(result) == 0 or result in self.__used_names:
            random_str = ''.join(random.sample(
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", random.randint(1, 2)))
            result = "%s%d" % (random_str, random.randint(1, 100))
        self.__used_names.append(result)
        return result


    # 生成变量
    def __generate_variable(self):
        var_scope = ["public", "private", "protected"]
        var_types = ["String", "int", "double", "float"]
        var_count = random.randint(3, 20)
        for i in range(0, var_count):
            code = "%s %s %s = " % (
                var_scope[random.randint(0, 2)],
                var_types[random.randint(0, 3)],
                self.__gen_rand_str()
            )
            if " String " in code:
                code += "\"%s\"" % self.__gen_rand_str()
            else:
                code += "%d" % random.randint(1, 1000)
            code += ";"
            self.__variables.append(code)

    #插入代码
    def __garble_java_file(self,file):
        with open(file,"r",encoding="utf-8") as fin:
            lines = fin.readlines()
        
        #初始化全局变量
        self.__generate_variable()
        with open(file,"w+",encoding="utf-8") as fout:
            for line in lines:
                # interface 不混淆
                # if "interface" in line and "{\n" in line:
                #     fout.write(line)
                #     continue
                #class下插入全局变量
                if (line.startswith("class ") or " class " in line) and "{" in line:
                    for var in self.__variables:
                        line +="%s\n"% var
                
                #只有一个缩进的方法，为类方法，可插入同级方法
                # func_re = re.compile(r'\s{4}[a-zA-Z](.*)[)]\s{0,}[{]')
                # result = func_re.match(line)
                # if result != None:
                #     print(result.group())
                # if :
            fout.write(line)
                
    def java_garble(self,config):
        __used_names = []
        __variables = []
        __functions = []
        for main_dir in config['lib_main']:
            for root, dirs, files in os.walk("%s/%s"%(config["root"],main_dir)):
                for file in files:
                    if file.endswith(".java"):
                        self.__garble_java_file(os.path.join(root,file))
