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

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


def script_second(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    logging.info('script_second: ' + str(channel_sdk_info))
    # 逆向渠道id
    modify_manifest(extract_dir, "hasFragileUserData")
    remove_value(extract_dir, "values-v31")
    remove_value(extract_dir, "color-v31")

    public_xml = os.path.join(extract_dir, "res/values/public.xml")
    handle_public_xml(public_xml ,"m3_ref_palette_dynamic_neutral")
    handle_public_xml(public_xml ,"m3_ref_palette_dynamic_primary")
    handle_public_xml(public_xml ,"m3_ref_palette_dynamic_secondary")
    handle_public_xml(public_xml ,"m3_ref_palette_dynamic_tertiary")
    handle_public_xml(public_xml ,"m3_sys_color_dynamic_dark")
    handle_public_xml(public_xml ,"m3_sys_color_dynamic_light")
    handle_public_xml(public_xml ,"material_dynamic_neutral")
    handle_public_xml(public_xml ,"material_dynamic_primary")
    handle_public_xml(public_xml ,"material_dynamic_secondary")
    handle_public_xml(public_xml ,"material_dynamic_tertiary")
    handle_public_xml(public_xml ,"m3_dynamic")

    handle_public_xml(public_xml, "cache_measures")
    handle_public_xml(public_xml, "dependency_ordering")
    handle_public_xml(public_xml, "graph")
    handle_public_xml(public_xml, "graph_wrap")
    handle_public_xml(public_xml, "grouping")
    handle_public_xml(public_xml, "ratio")
    sdk_id =  channel_sdk_info['id']
    if sdk_id == "597" :#深圳 成都都是用这个id
        public_xml = os.path.join(extract_dir, "res/values/public.xml")
        handle_public_xml(public_xml, "attr-private")

        public_xml = os.path.join(extract_dir, "res/layout/design_bottom_sheet_dialog.xml")
        handle_public_xml(public_xml, "attr-private")

        public_xml = os.path.join(extract_dir, "res/layout/mtrl_layout_snackbar.xml")
        # handle_public_xml(public_xml, "attr-private")
        os.remove(public_xml)

        public_xml = os.path.join(extract_dir, "res/layout-sw600dp/mtrl_layout_snackbar.xml")
        # handle_public_xml(public_xml, "attr-private")
        os.remove(public_xml)

        public_xml = os.path.join(extract_dir, "res/values/public.xml")
        handle_public_xml(public_xml, "mtrl_layout_snackbar")

        public_xml = os.path.join(extract_dir, "res/layout/mtrl_layout_snackbar_include.xml")
        handle_public_xml(public_xml, "attr-private")

        public_xml = os.path.join(extract_dir, "res/drawable-v21/abc_dialog_material_background.xml")
        handle_public_xml(public_xml, "attr-private")

        public_xml = os.path.join(extract_dir, "res/values/styles.xml")
        handle_public_xml(public_xml, "attr-private")

        public_xml = os.path.join(extract_dir, "res/values-v21/styles.xml")
        handle_public_xml(public_xml, "attr-private")

    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')


def remove_value(decompileDir, remove_dir):
    tmp_res = os.path.join(decompileDir, "res", remove_dir)
    if os.path.exists(tmp_res):
        distutils.dir_util.remove_tree(tmp_res)
if __name__ == '__main__':
    # replace_super_application("D:\work\wzdq")
    modify_manifest("E:\\apk\\youhua\\youhua.zip.out", "requestLegacyExternalStorage")
