# encoding: utf-8
import re

__author__ = 'pengtao'

import logging
import os
import yaml
import xml.etree.ElementTree as ET
import re

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


def script(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    print("")
    xmlparse(decompileDir)


def script_last(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    print("")
    replace_rose_resource(decompileDir)
    fix_install_fail_bug(decompileDir)
    fix_android8_bug_rose(decompileDir)
    fix_rose_recharge_screen_orientation(decompileDir)


def fix_rose_recharge_screen_orientation(decompile_dir_path):
    developer_path = os.path.join(decompile_dir_path, 'assets', 'developer.properties')
    print(developer_path)
    is_landscape = True
    with open(developer_path, 'r') as f:
        smali_str_arr = f.readlines()
        for line in smali_str_arr:
            if 'screen_oriention' in line:
                results = re.findall(re.compile(r'\d'), line)
                if len(results) != 0:
                    orientation_value = results[0]
                    print('orientation_value', orientation_value)
                    is_landscape = int(orientation_value) == 0
                    break
    print('is_landscape', is_landscape)
    namespace = '{http://schemas.android.com/apk/res/android}'
    ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
    manifest_path = os.path.join(decompile_dir_path, 'AndroidManifest.xml')
    xml_tree = ET.parse(manifest_path)
    xml_root = xml_tree.getroot()
    activity_nodes = xml_root.findall('.//activity')
    print(activity_nodes)
    for activity_node in activity_nodes:
        print(activity_node.attrib)
        activity_name = activity_node.get('%sname' % namespace)
        print(activity_name)
        if 'com.wanwu.sdkkit.gameplatform.activity.RechargeActivity' == activity_name:
            if is_landscape:
                activity_node.set('%sscreenOrientation' % namespace, 'landscape')
            else:
                activity_node.set('%sscreenOrientation' % namespace, 'portrait')
            xml_tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
            break


def fix_android8_bug_rose(decompile_dir):
    style_xml_path = os.path.join(decompile_dir, 'res', 'values', 'styles.xml')
    xml_tree = ET.parse(style_xml_path)
    xml_root = xml_tree.getroot()
    style_roots = xml_root.findall('./style')
    for style_root in style_roots:
        if style_root.get('name') == 'ydzs_splash_translucent':
            items = style_root.findall('./item')
            for item in items:
                print('item name', item.get('name'))
                print(item.findtext('.'))
                if item.get('name') == 'android:windowIsTranslucent':
                    item.text = 'false'
            xml_tree.write(style_xml_path, encoding='utf-8', xml_declaration=True)
            break
    namespace = '{http://schemas.android.com/apk/res/android}'
    ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
    manifest_path = os.path.join(decompile_dir, 'AndroidManifest.xml')
    xml_tree = ET.parse(manifest_path)
    xml_root = xml_tree.getroot()
    act_list = xml_root.findall('.//activity')
    for act in act_list:
        act_name = act.get('%sname' % namespace)
        print(act_name)
        if 'com.wanwu.sdkkit.gameplatform.activity.RechargeActivity' == act_name:
            act_theme = act.get('%stheme' % namespace)
            print('act_theme', act_theme)
            act.set('%stheme' % namespace, '@style/ydzs_splash_translucent')
            xml_tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
            break


def xmlparse(decompileDir):
    ET.register_namespace("android",ANDROID_NS)
    xmlpath = os.path.join(decompileDir, 'AndroidManifest.xml')
    root_node = ET.parse(xmlpath)
    root = root_node.getroot()
    name = '{' + ANDROID_NS + '}name'
    authorities = '{' + ANDROID_NS + '}authorities'
    package_name = root.attrib.get('package')

    if package_name is None:
        return
    providers = root.findall("./application/provider")
    if providers != None:
        for provider in providers:
            providerName = provider.attrib.get(name)

            if 'android.support.haojieru.v4.content.FileProvider' == providerName:
                provider.set(authorities, package_name + '.rose2.fileProvider')
    root_node.write(xmlpath, 'utf-8')

def fix_install_fail_bug(decompile_dir_path):
    namespace = '{http://schemas.android.com/apk/res/android}'
    ET.register_namespace('android', 'http://schemas.android.com/apk/res/android')
    manifest_path = os.path.join(decompile_dir_path, 'AndroidManifest.xml')
    xml_tree = ET.parse(manifest_path)
    xml_root = xml_tree.getroot()
    application_node = xml_root.find('./application')
    etract_value = application_node.get('%sextractNativeLibs' % namespace)
    if etract_value is not None and etract_value == 'false':
        # 修改extractNativeLib
        application_node.set('%sextractNativeLibs' % namespace, 'true')
        xml_tree.write(manifest_path, encoding='utf-8', xml_declaration=True)

    yaml_path = os.path.join(decompile_dir_path, 'apktool.yml')
    file = open(yaml_path, 'r')
    yaml_result = yaml.load(file, Loader=yaml.BaseLoader)
    sdk_info = yaml_result['sdkInfo']
    yaml_result['packageInfo']['renameManifestPackage'] = None
    print(sdk_info)
    if sdk_info.has_key('targetSdkVersion') and int(sdk_info['targetSdkVersion']) > 29:
        sdk_info['targetSdkVersion'] = '29'
        print(sdk_info)
        file.close()
        with open(yaml_path, 'w') as f:
            # yaml.dump(yaml_result, f)
            yaml.safe_dump(yaml_result, f,allow_unicode=True, default_flow_style=False)

def find_r_smali_and_replace(smali_file_path, regex_str):
    with open(smali_file_path, 'r') as f:
        smali_str = f.read()
        pattern = re.compile(regex_str)
        resource_arr = pattern.findall(smali_str)
        if len(resource_arr) > 0:
            print(smali_file_path)
        for r_str in resource_arr:
            virtual_name = r_str[r_str.index(' ') + 1:r_str.index(',')]
            print(virtual_name)
            resource_type = r_str[r_str.index('R$') + 2:r_str.index(';')].capitalize()
            print(resource_type)
            resource_name = r_str[r_str.index('->') + 2:r_str.index(':')]
            print(resource_name)
            new_r_str = "const-string %s, \"%s\"\n\n\tinvoke-static {%s}, Lcom/ydzs/framework/MommyUtils;->get%sId(Ljava/lang/String;)I\n\n\tmove-result %s" % (
                virtual_name, resource_name, virtual_name, resource_type, virtual_name)
            print(new_r_str)
            smali_str = smali_str.replace(r_str, new_r_str)
    with open(smali_file_path, 'w') as f:
        f.write(smali_str)


def replace_rose_resource(d_dir):
    r_regex_str = r'sget[^\n]*R\$layout[^\n]*I|sget[^\n]*R\$id[^\n]*I|sget[^\n]*R\$drawable[^\n]*I|sget[^\n]*R\$string[^\n]*I|sget[^\n]*R\$array[^\n]*I|sget[^\n]*R\$bool[^\n]*I|sget[^\n]*R\$integer[^\n]*I'
    for dirpath, dirnames, filenames in os.walk(d_dir):
        if r'com\ydzs' in dirpath:
            for smali_file in filenames:
                smali_file_path = os.path.join(dirpath, smali_file)
                # print(smali_file_path)
                find_r_smali_and_replace(smali_file_path, r_regex_str)


if __name__ == '__main__':
    xmlparse("D:/x7debug")

