# -*-coding:utf-8-*-
from utils import Utils
import random
import sys
import os
import re


class BuildConfig:
    # 随机生成包名
    @staticmethod
    def new_appid(app_name):
        app_name = app_name.replace(" ", "").lower()
        start_name = ["com", "cn", "id", "app", "host", "in"]
        middle_name = ["android", "main", "home", "base", "play", "release", "full", "kredit", "cepat",
                       "saku", "wallet", "coin", "loan", "flash", "pjnm", "indo", "lib"]
        # start
        pkg_name = start_name[random.randint(
            0, len(start_name) - 1)] + "." + app_name
        # middle
        length = random.randint(1, 3)
        for i in range(0, length):
            pkg_name += "." + \
                middle_name[random.randint(0, len(middle_name) - 1)]
        # end
        random_str = ''.join(random.sample(
            "abcdefghijklmnopqrstuvwxyz", random.randint(4, 8)))
        pkg_name += "." + random_str
        return pkg_name

    # 加载shell变量
    @staticmethod
    def load_properties(path):
        with open(path, "r", encoding="utf-8") as f:
            lines = f.readlines()

        config = {}
        for line in lines:
            if "=" in line:
                key = Utils.clearStr(line.split("=")[0], ["\"", "\'", "\n"])
                value = Utils.clearStr(line.split("=")[1], ["\"", "\'", "\n"])
                config[key] = value
        return config

    # 创建签名文件
    @staticmethod
    def new_keystore(config):
        # 只保留最近10个签名
        count = 0
        for root, dirs, files in os.walk(config['jks_path']):
            for name in files:
                count += 1
                if count > 10:
                    os.remove(os.path.join(root, name))

        # 创建签名文件
        key_name = config['app_name'].replace(" ", "")+config['version_code']
        command = "keytool -genkey" + " -alias <key_name> -keypass <key_name> -storepass <key_name>" \
            + " -dname \"CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown\"" \
            + " -keyalg RSA -validity 20000 -keystore <path>/<key_name>.keystore"
        command = command.replace("<key_name>", key_name).replace(
            "<path>", config["jks_path"])
        os.system(command)

        # 更新签名配置
        jks_path = "%s/%s.keystore" % (config["jks_path"], key_name)
        reset = {
            "signing_keyAlias": key_name,
            "signing_certificate": jks_path,
            "signging_certificatePassword": key_name,
            "signging_storePassword": key_name,
        }
        BuildConfig.update_properties(config, reset)

    # 更新properties字段
    @staticmethod
    def update_properties(config, dict):
        file_content = ""
        replace_line = {}
        with open(config['properties'], "r", encoding="utf-8") as f:
            file_content = f.read()
            for key in dict.keys():
                info = re.compile(r''+key+"=(.*)\n")
                targetLine = info.search(file_content).group()
                newLine = "%s=%s\n" % (key, dict[key])
                replace_line[targetLine] = newLine
            for key in replace_line.keys():
                print(replace_line[key])
                file_content = file_content.replace(key, replace_line[key])

        with open(config['properties'], "w", encoding="utf-8") as f_w:
            f_w.write(file_content)
