# coding:utf8

__author__ = 'dong'

import os
import logging
import xml.dom.minidom
import re
import shutil
import glob
from xml.etree.ElementTree import ElementTree, Element
import distutils.dir_util
import gw_file_system
from xml.etree import ElementTree as ET

ANDROID_NS = 'http://schemas.android.com/apk/res/android'


def script(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    s1 = os.path.join(decompileDir, "smali", "com")
    s3 = os.path.join(decompileDir, "smali_classes4", "com")
    list_package = ["android", "connect", "dynamicbundle", "haowanyou", "mm", "open", "tauth", "utx", "wysd", "yeepay",
                    "tencent", "qihoo", "hjr"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    move_package(s1, s3, list_package)

    s1 = os.path.join(decompileDir, "smali")
    s3 = os.path.join(decompileDir, "smali_classes4")
    list_package = ["org", "sdk", "retrofit2"]
    move_package(s1, s3, list_package)

    # smali_classes3方法数超出
    s1 = os.path.join(decompileDir, "smali_classes3", "com")
    smali_classes_new = create_mutil_smali(decompileDir)
    s3 = os.path.join(decompileDir, smali_classes_new, "com")
    list_package = ["huawei", "heytap", "heepay", "google", "cloudplay"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    move_package(s1, s3, list_package)

    arm64 = os.path.join(decompileDir, "lib", "arm64-v8a")
    if os.path.exists(arm64):
        distutils.dir_util.remove_tree(arm64)
    logging.info("-----debug-----")

    sdk_id = channelSdkInfo['id']
    if sdk_id == "323":
        modify_manifest(decompileDir)
        modify_manifest_common(decompileDir, "requestLegacyExternalStorage")
    return


def script_last(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    logging.info('------------channelSdkInfo:' + str(channelSdkInfo))
    if channelSdkInfo['SDKName'] == 'reversefor360':
        replace_super_application(decompileDir)

    if channelSdkInfo['id'] == "549" or channelSdkInfo['id'] == "234":
        s1 = os.path.join(decompileDir, "smali")
        smali_classes_new = create_mutil_smali(decompileDir)
        s3 = os.path.join(decompileDir, smali_classes_new)
        list_package = ["androidx"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

        s1 = os.path.join(decompileDir, "smali_classes5/com")
        smali_classes_new = create_mutil_smali(decompileDir)
        s3 = os.path.join(decompileDir, smali_classes_new)
        list_package = ["friendtime", "friendtimes", "ft", "GF"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

    return


def move_package(s1, s3, list_package):
    for d in list_package:
        src = os.path.join(s1, d)
        if os.path.exists(src):
            dst = os.path.join(s3, d)
            distutils.dir_util.copy_tree(src, dst)
            distutils.dir_util.remove_tree(src)


change_map = {".super Landroid/app/Application;": ".super Lcom/kf/framework/KFApplication;",
              "invoke-direct {p0}, Landroid/app/Application;-><init>()V": "invoke-direct {p0}, Lcom/kf/framework/KFApplication;-><init>()V",
              "invoke-super {p0, p1}, Landroid/app/Application;->attachBaseContext(Landroid/content/Context;)V": "invoke-super {p0, p1}, Lcom/kf/framework/KFApplication;->attachBaseContext(Landroid/content/Context;)V",
              "invoke-super {p0, p1}, Landroid/app/Application;->onConfigurationChanged(Landroid/content/res/Configuration;)V": "invoke-super {p0, p1}, Lcom/kf/framework/KFApplication;->onConfigurationChanged(Landroid/content/res/Configuration;)V",
              "invoke-super {p0}, Landroid/app/Application;->onLowMemory()V": "invoke-super {p0}, Lcom/kf/framework/KFApplication;->onLowMemory()V",
              "invoke-super {p0}, Landroid/app/Application;->onTerminate()V": "invoke-super {p0}, Lcom/kf/framework/KFApplication;->onTerminate()V",
              "invoke-super {p0, p1}, Landroid/app/Application;->onTrimMemory(I)V": "invoke-super {p0, p1}, Lcom/kf/framework/KFApplication;->onTrimMemory(I)V",
              "invoke-super {p0}, Landroid/app/Application;->onCreate()V": "invoke-super {p0}, Lcom/kf/framework/KFApplication;->onCreate()V", }


def replace_super_application(decompileDir):
    smali_files = glob.glob(os.path.join(decompileDir, 'smali*/sdk/bjm/BJMApplication.smali'))
    if len(smali_files) == 1:
        game_application_file = smali_files[0]
        print game_application_file
        if os.path.isfile(game_application_file):
            with open(game_application_file, "r+") as f:
                file_str = f.read()
                for k, v in change_map.items():
                    file_str = file_str.replace(k, v)
            with open(game_application_file, "w+") as f:
                f.write(file_str)


def create_mutil_smali(decompileDir):
    f_idx = 2
    while True:
        tmp = gw_file_system.get_full_path(os.path.join(decompileDir, 'smali_classes%d' % f_idx))
        tmp = tmp.replace('\\', '/')
        tmp = re.sub('/+', '/', tmp)
        if os.path.exists(tmp):
            f_idx += 1
        else:
            smali_classes2_dir = tmp
            break
    # endwhile
    os.mkdir(smali_classes2_dir)
    return smali_classes2_dir


def modify_manifest(decompileDir):
    ET.register_namespace('android', ANDROID_NS)
    xmlparse = os.path.join(decompileDir, 'AndroidManifest.xml')
    root_node = ET.parse(xmlparse)
    root = root_node.getroot()
    name = '{' + ANDROID_NS + '}name'
    authorities = '{' + ANDROID_NS + '}foregroundServiceType'
    package_name = root.attrib.get('package')
    if package_name == None:
        return
    providers = root.findall('./application/service')
    if providers != None:
        for provider in providers:
            providerName = provider.attrib.get(name)
            if 'com.netease.cc.screen_record.codec.screencapture.ScreenCaptureService' == providerName:
                # 使用try 主要是为了 防止此属性不在时，导致的错误，而程序终止
                try:
                    del provider.attrib[authorities]
                except:
                    ""

    root_node.write(xmlparse, 'utf-8')


def modify_manifest_common(decompileDir, removeKey):
    ET.register_namespace('android', ANDROID_NS)
    xmlparse = os.path.join(decompileDir, 'AndroidManifest.xml')
    root_node = ET.parse(xmlparse)
    root = root_node.getroot()
    name = '{' + ANDROID_NS + '}name'
    authorities = '{' + ANDROID_NS + '}' + removeKey
    package_name = root.attrib.get('package')
    if package_name == None:
        return
    providers = root.findall('./application')
    if providers != None:
        for provider in providers:
            # providerName = provider.attrib.get(name)
            # if 'com.netease.ntunisdk.CcMomentRecordingForegroundService' == providerName:
            # 使用try 主要是为了 防止此属性不在时，导致的错误，而程序终止
            try:
                del provider.attrib[authorities]
            except:
                ""

    root_node.write(xmlparse, 'utf-8')


if __name__ == '__main__':
    replace_super_application("D:\\work\\bh")
