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


class LayoutGarble:
    __used_names = []
    __layout_model = []
    __config = {}
    __colors = []

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

    def __rand_item(self, values):
        return values[random.randint(0, len(values)-1)]

    def __set_values(self, attrs):
        gravity = ['center_vertical', 'center_horizontal',
                   'left', 'right', 'bottom', 'top']
        visibility = ['visible', 'invisible', 'gone']
        boolean = ['true', 'false']
        size = ['wrap_content', 'match_parent', '${number}dp']
        orientation = ['horizontal', 'vertical']
        scale_type = ['fitCenter', 'centerCrop', 'center',
                      'fitXY', 'centerInside', 'fitEnd', 'fitStart', 'matrix']

        return attrs.replace("${id}", self.__gen_rand_str())\
            .replace("${string}", self.__gen_rand_str())\
            .replace("${color}", self.__rand_item(self.__colors))\
            .replace("${gravity}", self.__rand_item(gravity))\
            .replace("${visibility}", self.__rand_item(visibility))\
            .replace("${boolean}", self.__rand_item(boolean))\
            .replace("${number}", "%d"%random.randint(0, 10000))\
            .replace("${size}", self.__rand_item(size).replace("${number}", "%d"%random.randint(0, 10000)))\
            .replace("${orientation}", self.__rand_item(orientation))\
            .replace("${scaleType}", self.__rand_item(scale_type))

    def __create_attributes(self):
        attrs = self.__layout_model[0].split("*\n")
        result = ""
        for i in range(random.randint(0, len(attrs)-1)):
            item = attrs[random.randint(0, len(attrs)-1)]
            while item.split("=")[0] in result:
                item = attrs[random.randint(0, len(attrs)-1)]
            result += "%s\n" % self.__set_values(item)
        return result

    def __create_views(self):
        view_model = self.__layout_model[2].split("@---sep---")
        views = ""
        for i in range(2,10):
            view = self.__rand_item(view_model)
            views += self.__set_values(view).replace("${attributes}", self.__create_attributes())
        return views

    def __create_layout(self, path):
        layouts = self.__layout_model[1].split("@---sep---")
        root_layout = self.__rand_item(layouts)
        root_layout = root_layout.replace(
            "${attributes}", "%s\n${attributes}" % "xmlns:android=\"http://schemas.android.com/apk/res/android\"")
        root_layout = self.__set_values(root_layout)
        content = ""
        for i in range(0,random.randint(0,20)):
            if random.randint(0,50) % random.randint(3,5) == 0:
                layout = self.__rand_item(layouts).replace("${attributes}", self.__create_attributes())
                layout.replace("${childs}",self.__create_views())
                content += layout
            else:
                content += self.__create_views()
        root_layout = root_layout.replace("${childs}",content)

        with open(path,"w+",encoding='utf-8') as fout:
            fout.write(root_layout)
                


    def layout_garble(self, config):
        self.__config = config
        with open("tools/garble/model/layout_model.xml", "r", encoding="utf-8") as fin:
            self.__layout_model = fin.read().split("@code\n")

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

        print("layout inserting ...")
        for main_dir in config['lib_main']:
            for root, dirs, files in os.walk("%s/%s" % (config["root"], main_dir)):
                if root.endswith("res/layout"):
                    self.__create_layout(os.path.join(
                        root, "%s.xml" % self.__gen_rand_str()))

        print("done")
