# 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
import gw_data_center
from xml.etree import ElementTree as ET

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):
    sdk_id = channel_sdk_info['id']
    gw_data_center.pack_small = False
    logging.info('script_init: ' + str(channel_sdk_info))


def script_first(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    logging.info("-----debug exec first func-----")
    # game_apk = os.path.join(decompileDir, "game.apk")
    game_apk = decompileDir + "/../game.apk"
    if os.path.exists(game_apk):
        # A3AEECD8
        gw_file_system.delete_apk_file_by_aapt(game_apk, "assets/39285EFA.dex")
    logging.info("-----debug-----")


def script(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    dex = decompileDir + "../39285EFA.dex"
    asserts = os.path.join(decompileDir, "assets/39285EFA.dex")
    if os.path.exists(asserts) and os.path.exists(os.path.join(dex)):
        distutils.dir_util.copy_tree(dex, asserts)
    logging.info("-----debug-----")

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


def script_last(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    logging.info('------------channelSdkInfo:' + str(channelSdkInfo))

    sdk_id = channelSdkInfo['id']
    if sdk_id == "323":
        s1 = os.path.join(decompileDir, "smali_classes2/com")
        if not os.path.exists(s1):
            return
        smali_classes2_dir = create_mutil_smali(decompileDir)
        s3 = os.path.join(smali_classes2_dir, "com")
        list_package = ["heepay", "heytap", "http", "huawei", "iapppay", "ipaynow"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

        s1 = os.path.join(decompileDir, "smali_classes2/com")
        if not os.path.exists(s1):
            return
        smali_classes2_dir = create_mutil_smali(decompileDir)
        s3 = os.path.join(smali_classes2_dir, "com")
        list_package = ["manjuu", "meizu"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

        s1 = os.path.join(decompileDir, "smali_classes2/com")
        if not os.path.exists(s1):
            return
        smali_classes2_dir = create_mutil_smali(decompileDir)
        s3 = os.path.join(smali_classes2_dir, "com")
        list_package = ["nearme", "onevcat", "qihoo"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)


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

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

def modify_manifest_exteral(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')


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)


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):
            files = os.listdir(tmp)
            if len(files) == 0:
                smali_classes2_dir = tmp
                break
            f_idx += 1
        else:
            smali_classes2_dir = tmp
            break
    # endwhile
    if not os.path.exists(smali_classes2_dir):
        os.mkdir(smali_classes2_dir)
    return smali_classes2_dir


if __name__ == '__main__':
    modify_manifest("E:/apk/youhua/IqUqCxOv3GgEq5sEOVuEdGphwje6AOnMT1n_ZMEjKCat9lugo-H2jraK5cquZ9lL0")
