# coding:utf8
import os
import xml.etree.ElementTree as ET
import logging
import re
import codecs

ANDROID_NAMESPACE = 'http://schemas.android.com/apk/res/android'
logger = logging.getLogger('script.py')

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


def script_second(sdk, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    sdk_id = channelSdkInfo["id"]
    if sdk_id == "512":
        update_applicationName(decompileDir)
        modify_manifest(decompileDir, "requestLegacyExternalStorage")
        modify_manifest(decompileDir, "hasFragileUserData")
    remove_public(decompileDir)


def remove_public(decompileDir):
    tmp_public_xml = os.path.join(decompileDir, "res", "values", "public.xml")
    if os.path.exists(tmp_public_xml):
        os.remove(tmp_public_xml)


def update_applicationName(decompileDir):
    manifestFile = decompileDir + '/AndroidManifest.xml'
    ET.register_namespace('android', ANDROID_NAMESPACE)
    key = '{' + ANDROID_NAMESPACE + '}name'
    targetTree = ET.parse(manifestFile)
    targetRoot = targetTree.getroot()
    applicationNode = targetRoot.find('application')

    if applicationNode is not None:
        applicationNode.set(key, "com.minitech.miniworld.coolpad" + ".MyWrapperProxyApplication")
        targetTree.write(manifestFile, 'UTF-8')
        return


def handle_public_xml(public_xml_path, remove_node):
    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(remove_node) > -1:
                continue
            new_lines.append(line)
        f.seek(0)
        f.truncate()
        f.writelines(new_lines)
    return


def modify_manifest(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__':
    script_last('', 'E:/script_test', {}, {}, {})
