# encoding: utf-8
import logging
import os
import yaml
import xml.etree.ElementTree as ET
import re
__author__ = 'billyyoyo'

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

def change_application_id(extra_dir, packageName):
    fname = extra_dir + '/AndroidManifest.xml'
    with open(fname, 'r+') as f:
        cont = f.read()
        findstr = '#applicationId#'
        rStr = packageName+'.smallsheep'
        cont = cont.replace(findstr, rStr)
        f.seek(0)
        f.truncate(len(cont))
        f.write(cont)
        f.close()

def fix_xmy_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)
    if not is_landscape:
        return
    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.yog.kothoth.view.activity.SSRechargeActivity' == activity_name:
            activity_node.set('%sscreenOrientation' % namespace, 'landscape')
            xml_tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
            break

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 fix_android8_bug_xmy(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') == 'kf_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.yog.kothoth.view.activity.SSShoppingMallActivity' == act_name or 'com.yog.kothoth.view.activity.SSRechargeActivity' == act_name:
            act_theme = act.get('%stheme' % namespace)
            print('act_theme', act_theme)
            act.set('%stheme' % namespace, '@style/kf_splash_translucent')
            xml_tree.write(manifest_path, encoding='utf-8', xml_declaration=True)
            break


def script(work_sdk_dir, extra_dir, channel_sdk_info, new_game_channel_info, game_info):
    logging.info("---------------channel_sdk_info-------------")
    logging.info(channel_sdk_info)
    logging.info("---------------new_game_channel_info-------------")
    logging.info(new_game_channel_info)
    logging.info("---------------game_info-------------")
    logging.info(game_info)
    applicationId = channel_sdk_info["packNameSuffix"]
    change_application_id(extra_dir, applicationId)
    fix_install_fail_bug(extra_dir)
    fix_xmy_recharge_screen_orientation(extra_dir)
    fix_android8_bug_xmy(extra_dir)

if __name__ == '__main__':
    script("", ".", {'package_name':'com.netease.dwrg.yl.ludashi'}, {}, {})
