# -*-coding:utf-8-*-
from tools.screen_maker import ScreenMaker
import random
import sys
import os
import io
import re
import shutil
import requests
import json
import chardet


class Function:
    # 随机生成包名
    def new_appid(self,config):
        app_name = config['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

        version_code = str(int(config['version_code'])+1)
        version_name = "#%s#"% version_code.replace("",".")
        version_name = version_name.replace("#.","").replace(".#","")
        lines = {
            "app_id": pkg_name,
            "version_code": version_code,
            "version_name": version_name
        }
        self.update_properties(config,lines)

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

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


    # 创建签名文件
    def new_keystore(self,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 = "../jks/%s.keystore" % key_name
        reset = {
            "signing_keyAlias": key_name,
            "signing_certificate": jks_path,
            "signging_certificatePassword": key_name,
            "signging_storePassword": key_name,
        }
        self.update_properties(config, reset)


    # 更新properties字段
    def update_properties(self,config, dict):
        file_content = ""
        replace_line = {}
        with open("%s/gradle.properties"%config['root'], "r", encoding="utf-8") as f:
            file_content = f.read()
            for key in dict.keys():
                info = re.compile(r''+key+"=(.*)\n")
                result = info.search(file_content)
                if result is not None:
                    targetLine = result.group()
                    newLine = "%s=%s\n" % (key, dict[key])
                    replace_line[targetLine] = newLine
                else:
                    print("%s 字段不存在 !!!"%key)
            for key in replace_line.keys():
                print(replace_line[key].replace("\n", ""))
                file_content = file_content.replace(key, replace_line[key])

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


    # 移动apk
    def move_apk(self,config):
        file_name = "%s_%s" % (
            config['corp_id'], config['app_name'].replace(" ", "_"))
        apk_local = "%s/resGuardApks/%s_release.apk" % (
            config['root'], file_name)
        apk1 = "/Users/connor/Documents/apks/%s.apk" % file_name
        apk2 = "/Users/connor/Documents/apks/%s/%s.apk" % (
            file_name, file_name)

        if os.path.exists("/Users/connor/Documents/apks/%s" % file_name):
            shutil.copy(apk_local, apk2)
        else:
            shutil.copy(apk_local, apk1)


    # FB秘钥散列
    def getFbSign(self,config):
        with open("%s/app/src/main/AndroidManifest.xml" % config['root'], "r") as f:
            file_content = f.read()
            info = re.compile(r'package=\"(.*)\"')
            package = info.search(file_content).group().split("=")[
                1].replace("\"", "")
            info = re.compile(r'\"(.*).SplashActivity\"')
            package += info.search(file_content).group().replace("\"", "")

            print("包名：" + config['app_id'])
            print("类名：" + package)
            print("散列：")
            command = "keytool -exportcert -alias <signing_keyAlias> -keystore app/<signing_certificate> -storepass <signing_keyAlias> | openssl sha1 -binary | openssl base64"
            command = command.replace("<signing_keyAlias>", config['signing_keyAlias'])\
                .replace("<signing_certificate>", config['signing_certificate'])
            os.system(command)


    # 更新Gateway
    def update_gateway(self,config):
        gateway = requests.get(config['gateway_url']).json()
        jsonStr = json.dumps(gateway).replace("http://", "https://")
        gateway = json.loads(jsonStr)

        ip = gateway['gateway'][0]
        if len(gateway['gateway']) > 1:
            ip = gateway['gateway'][1]

        harvest = gateway['harvester'][0].replace("https://","")
        replaces = {
            "base_url": "\"%s\"" % gateway['rest'][0],
            "harvest_ip": "\"%s\"" % harvest.split(":")[0],
            "harvest_port": "%s" % harvest.split(":")[1],
            "gateway_url": "\"%s\"" % gateway['gateway'][0],
            "gateway_ip": "\"%s\"" % ip,
            "repayment_h5": "\"%s\"" % gateway['repay'][0],
            "admin_host": "\"%s\"" % gateway['admin'][0],
            "agreement_url": "\"%s\"" % gateway['privacy'][0],
            "home": "\"%s\"" % gateway['home'][0],
        }
        self.update_properties(config, replaces)


    # 切换主包马甲包
    def cutover(self,config):
        print("1、切换到主包")
        print("2、切换到马甲包")

        img_path = "%s/app/src/main/res/drawable-xxhdpi/" % config['root']
        command = int(input("选择包类型："))
        if command == 1:
            shutil.copy(img_path+"logo_main.png", img_path+"logo.png")
            # 主包混淆文件
            if os.path.exists("%s/script/api_mapping" % config['root']):
                os.remove("%s/script/api_mapping" % config['root'])
            shutil.copy("%s/script/api_mapping_main" %
                        config['root'], "%s/script/api_mapping" % config['root'])

            replace_lines = {
                "app_name": config['main_name'],
                "gateway_url": "\"%s\"" % config['gateway_main'],
                "host_app": "true"
            }
            config['gateway_url'] = config['gateway_main']
            # 更新gw
            self.update_properties(config, replace_lines)
            self.update_gateway(config)

        elif command == 2:
            shutil.copy(img_path+"logo_majia.png", img_path+"logo.png")
            # 马甲混淆文件替换
            if os.path.exists("%s/script/api_mapping" % config['root']):
                os.remove("%s/script/api_mapping" % config['root'])
            shutil.copy("%s/script/api_mapping_majia" %
                        config['root'], "%s/script/api_mapping" % config['root'])

            replace_lines = {
                "app_name": config['majia_name'],
                "gateway_url": "\"%s\"" % config['gateway_mj'],
                "host_app": "false"
            }
            config['gateway_url'] = config['gateway_mj']
            # 更新gw
            self.update_properties(config, replace_lines)
            self.update_gateway(config)

    # 创建描述文件
    
    def create_desc(self,config):
        desc = ""
        with open("/Users/connor/StudioProjects/WorkSpace/app_desc.txt", "r") as f:
            file_content = f.read().replace("\n", "--line--")
            index = random.randint(1, 42)
            print("模板%d"%index)
            info = re.compile(
                r''+"@Example %d--line--(.*)@End %d" % (index, index))
            desc = info.search(file_content).group()

            desc = desc.replace("--line--", "\n")\
                .replace("@Example %d\n" % index, "")\
                .replace("@End %d" % index, "")

        file_name = "%s_%s"\
            % (config['corp_id'], config['app_name'].replace(" ", "_"))
        output = "/Users/connor/Documents/apks/%s/%s.txt" % (
            file_name, file_name)
        with open(output, "w+") as f_w:
            desc = desc.replace("${email}", config['cus_email'])\
                .replace("${app_name}", config['app_name'])\
                .replace("${phone_num}", config['hot_line'])\
                .replace("${address}", config['cus_adress'])
            f_w.write(desc)


    # 打印checklist
    def print_checklist(self,config, just_print):
        print(" ")
        print("%s %s" % (config['corp_id'], config['app_name']))
        print("包名：%s" % config['app_id'])
        print("对内协议：%s" % config['agreement_url'])
        print("对外协议：%s/privacy.html" % config['home'])
        print(" ")
        if just_print:
            return

        file_name = "%s_%s"\
            % (config['corp_id'], config['app_name'].replace(" ", "_"))
        target = "/Users/connor/Documents/apks"
        img_path = "../../app/src/main/res/drawable-xxhdpi"

        if not os.path.exists(target+"/"+file_name):
            os.makedirs(target+"/"+file_name)

        self.create_desc(config)    

        try:
            shutil.move("%s/%s.apk" % (target, file_name),
                        "%s/%s/%s.apk" % (target, file_name, file_name))
            shutil.move("%s/%s.html" % (target, file_name),
                        "%s/%s/%s.html" % (target, file_name, file_name))
        except:
            print("没有找到 apk 或 隐私协议 文件")

        shutil.copy("%s/logo.png" % img_path, "%s/%s/logo.png" %
                    (target, file_name))
        shutil.copy("%s/top.png" % img_path, "%s/%s/top.png" %
                    (target, file_name))

        screen = ScreenMaker()
        screen.draw_bg(img_path+"/bg01.png", img_path+"/logo.png",
                       img_path+"/top.png", "/Users/connor/Documents/apks/"+file_name)
        print("截图制作完成")


    # 更新本地隐私协议
    def update_local_privacy(self,config):
        path = config['root'] + "/app/src/main/assets/web/"
        if not os.path.exists(path):
            os.makedirs(path)
        resp = requests.get(config['agreement_url'])
        content = resp.text
        encode = chardet.detect(resp.content)['encoding']
        with io.open(path+"privacy.html", "w+", encoding=encode) as fout:
            fout.write(content)
            print("本地协议已更新！" + config['agreement_url'])

        ksp_url = config['agreement_url'].replace(".html", "Ksp.html")
        resp = requests.get(ksp_url)
        content = resp.text
        encode = chardet.detect(resp.content)['encoding']
        if "<Code>NoSuchKey</Code>" not in content:
            with io.open(path+"privacyKsp.html", "w+", encoding=encode) as fout:
                fout.write(content)
                print("本地KSP协议已更新！" + ksp_url)


    # 创建新协议
    def new_privacy(self,config):
        permissions = "1235"
        if config['contact'] != "true":
            permissions = "235"
        file_name = "%s_%s" % (config['corp_id'], config['app_name'].replace(" ","_"))
        print("path url:  %s/privacy1.html" % config['home'])

        with open("/Users/connor/Documents/apks/privacy/privacy0.html", "rt") as fin:
            file_content = fin.read()

        file_content = file_content.replace("${app_name}", config['app_name'])
        file_content = file_content.replace("${permission_list}", permissions)

        with open("/Users/connor/Documents/apks/%s.html" % file_name, "wt") as fout:
            fout.write(file_content)
        print("privacy done\n")



    # 转移出所有素材
    def move_resources(self,config):
        target = "/Users/connor/Documents/apks"
        img_path = "../../app/src/main/res/drawable-xxhdpi"

        
        if not os.path.exists(target+"/cache"):
            os.makedirs(target+"/cache")
        else:
            shutil.rmtree(target+"/cache")
            os.makedirs(target+"/cache")

        # 移除
        shutil.copy("%s/logo.png" % img_path, "%s/cache/logo.png" % target)
        try:
            shutil.copy("%s/top.png" % img_path, "%s/cache/top.png" % target)
            shutil.copy("%s/script/api_mapping" %
                    config['root'], "%s/cache/api_mapping" % target)
        except:
            print("out: no api_mapping or img")

        new_config = config.copy()
        new_config.update(self.load_properties("../../gradle.properties"))

        os.system("cd %s\ngit reset --hard origin/%s" % (config['root'],config['git_branch']))

        # 还原
        shutil.copy("%s/cache/logo.png" % target, "%s/logo.png" % img_path)
        try:
            os.remove("%s/script/api_mapping" % config['root'])
        except:
            print("")

        try:
            shutil.copy("%s/cache/top.png" % target, "%s/top.png" % img_path)
            shutil.copy("%s/cache/api_mapping" %
                        target, "%s/script/api_mapping" % config['root'])
        except:
            print("in: no api_mapping or img")

        self.update_gateway(new_config)

        lines = {
            "app_id": "%s" % new_config['app_id'],
            "app_name": "%s" % new_config['app_name'],
            "signing_keyAlias": "%s" % new_config['signing_keyAlias'],
            "signing_certificate": "%s" % new_config['signing_certificate'],
            "signging_certificatePassword": "%s" % new_config['signging_certificatePassword'],
            "signging_storePassword": "%s" % new_config['signging_storePassword'],
        }
        self.update_properties(config, lines)
