import random
import os
from tools.garble.class_builder import ClassBuilder

class ManifestGarble:
    __used_names = []
    def __gen_rand_str(self):
        result = ""
        while len(result) == 0 or result in self.__used_names:
            random_str = ''.join(random.sample(
                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", random.randint(6, 10)))
            result = "%s%d" % (random_str, random.randint(101, 200))
        self.__used_names.append(result)
        return result

    #在包中随机创建Activity
    def __create_activities(self,path):
        activities = []
        for root, dirs, files in os.walk(path):
            if len(files) > 0 and (files[0].endswith(".java") or files[0].endswith(".kt")):
                for i in range(0,random.randint(3,10)):
                    act_name = self.__gen_rand_str()
                    act_path = "%s/%s.java"%(root, act_name) 
                    pkg_name = root.split("main/java/")[1].replace("/",".")
                    act_content = ClassBuilder().new_class(act_name,pkg_name)
                    with open(act_path, "w+", encoding="utf-8") as fout:
                        fout.write(act_content)
                    activities.append("%s.%s"%(pkg_name,act_name))
        return activities

    
    def __insert_to_manifest(self,path,activities):
        file_content = ""
        with open(path,"r",encoding="utf-8") as fin:
            file_content = fin.read()

        for activity in activities:
            code = "<activity android:name=\"%s\" />"%activity
            file_content = file_content.replace("</application>","%s\n</application>"%code)
        
        with open(path,"w",encoding="utf-8") as fout:
            fout.write(file_content)

        

    def manifest_garble(self, config):
        for main_dir in config['lib_main']:
            print("activity generating  ...")
            activities = self.__create_activities("%s/%s/java"%(config["root"], main_dir))
            print("inster activity to manifest ...")
            self.__insert_to_manifest("%s/%s/AndroidManifest.xml"% (config["root"], main_dir), activities)
        
        print("done")
