from PIL import Image
from PIL import ImageDraw
import random
import os
import json
import sys
import time

class ImageGarble:
    __colors = []

    __used_names = []
    # 随机串

    def __gen_rand_str(self):
        result = ""
        while len(result) == 0 or result in self.__used_names:
            result = ''.join(random.sample(
                "abcdefghijklmnopqrstuvwxyz", random.randint(5, 15)))
        self.__used_names.append(result)
        return result

    def __create_img(self, imgPath):
        size = len(self.__colors)
        image = Image.new('RGBA', (random.randint(1, 50), random.randint(
            1, 50)), self.__colors[random.randint(0, size-1)])
        image.save(imgPath, quality=10)

    def img_garble(self, config):
        with open("tools/garble/model/colors.json", "r", encoding="utf-8") as fin:
            self.__colors = json.loads(fin.read())

        count = 0
        print("generating image ...")
        for main_dir in config["lib_main"]:
            for root, dirs, files in os.walk("%s/%s/res/" % (config['root'], main_dir)):
                #改变现有图片MD5
                for file in files:
                    if file.endswith(".png") or file.endswith(".webp"):
                        with open(os.path.join(root,file),"a") as f:
                            path = os.path.join(root,file)
                            with open(path,"a") as f:
                                f.write(str(time.time()+random.randint(1,10000)))
                #创建随机图片
                if len(files) > 0 and (".png" in str(files) or ".webp" in str(files)) :
                    print(root)
                    for i in range(0, random.randint(30, 50)):
                        #最多500张
                        if count > 500:
                            return
                        # img_path = "/Users/connor/Documents/apks/imgs/%s.png"%self.__gen_rand_str()
                        # self.__create_img(img_path)
                        self.__create_img("%s/%s.png"%(root,self.__gen_rand_str()))
                        count += 1
        print("done")
        print("已生成%d张图片"% count)
