# coding:utf8
import os
import logging
import re
import glob
import shutil
import xml.etree.ElementTree as ET
import gw_data_center
import gw_apk_tool
import distutils.dir_util

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


def script_init(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    gw_data_center.pack_small = False
    logging.info('script_init: ' + str(channel_sdk_info))


def script_last(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    s1 = os.path.join(extract_dir, "smali_classes3")
    s2 = os.path.join(extract_dir, "smali_classes3", "androidx")
    if os.path.exists(s2):
        smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
        s3 = smali_classes2_dir
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        gw_apk_tool.move_package(s1, s3, ["androidx"])

    sdk_id = channel_sdk_info['id']
    if sdk_id == "512" or sdk_id=="589":
        move(extract_dir)
    else:
       move_smallsheep(extract_dir)
    return


def move(extract_dir):
    s1 = os.path.join(extract_dir, "smali_classes5", "com")
    smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir, "com")
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, ["netease"])

def move_smallsheep(extract_dir):
    s1 = os.path.join(extract_dir, "smali_classes4", "androidx")
    smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir, "androidx")
    move_page=["interpolator","lifecycle","localbroadcastmanager","print","slidingpanelayout","tracing","versionedparcelable","legacy","loader","media","savedstate","swiperefreshlayout","vectordrawable","viewpager"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, move_page)

    s1 = os.path.join(extract_dir, "smali_classes6", "com/netease")
    smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir, "com/netease")
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, ["ntunisdk","pharos","screen_recorder","sr101","tx","unifix","unisdk","utils","videoedit"])


def script_pre(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    sdk_id = channel_sdk_info['id']
    if sdk_id == "512" or sdk_id=="589":
        modify_manifest(extract_dir)
        game_mode_config = os.path.join(extract_dir, "res/xml-v22/game_mode_config.xml")
        os.remove(game_mode_config)



def intoFirstLine(target, repl, cont):
    # srcStr = "onBackPressed"
    # regexp = '.method (?:public|protected) +?'+target+"\([^.]+?\.locals +[0-9]{1,2}"
    regexp = '.method (?:public|protected) +?' + target + "\([^.]+?\.locals +([0-9]{1,2})"
    # print(regexp)
    reObj = re.compile(regexp)
    matchO = reObj.search(cont)
    if matchO:
        # print(matchO.group(0))
        methodHead = matchO.group(0)
        if matchO.group(1) == "0":
            methodHead = re.sub("locals +0", "locals 1", methodHead)

        repl = methodHead + r'\n\n    ' + repl + r'\n\n'
        cont = reObj.sub(repl, cont)
    else:
        # todo call .super method
        cont += r'.method protected ' + target + r'()V\n\n    .locals 0\n\n    ' + repl + r'\n\n    .end method\n'

    return cont


def fixLifecycleMethod(preDir):
    for tfile in glob.glob(preDir + "/" + "smali*/org/bojoy/publish/PublishActivity.smali"):
        if os.path.isfile(tfile):
            with open(tfile, 'r+') as f:
                cont = f.read()
                changes = {
                    "onCreate": "invoke-static {p0}, Lcom/baidu/gamesdk/BDGameSDK;->setContext(Landroid/app/Activity;)V",
                }
                for k, v in changes.iteritems():
                    cont = intoFirstLine(k, v, cont)

                f.seek(0)
                f.write(cont)
                f.close()


def handle_public_xml(public_xml_path):
    if not os.path.exists(public_xml_path):
        logging.info('public_xml is null: ' + public_xml_path)
        return
    new_lines = []
    with open(public_xml_path, 'r+') as f:
        for line in f.readlines():
            # l = line.strip()
            if line.find("qihoo_game_sdk_authenticator") > -1:
                continue
            new_lines.append(line)
        f.seek(0)
        f.truncate()
        f.writelines(new_lines)
    return


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.ntunisdk.CcMomentRecordingForegroundService' == providerName:
                # 使用try 主要是为了 防止此属性不在时，导致的错误，而程序终止
                try:
                    del provider.attrib[authorities]
                except:
                    ""

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


if __name__ == '__main__':
    # script("/tmp/ss", "/mnt/share/yanghuang/python_test/any_dir", {"id": "309"}, "", "")
    xml_path = "E:/apk/youhua/jingmenfengyue_216122/res/values/public.xml"
    handle_public_xml(xml_path)
    # hideSplash("/mnt/share/yanghuang/python_test/cr")
