# -*- coding:utf-8 -*-
__author__ = 'Snow'

import yaml
import os
import re
import logging

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'

def findRSmaliAndReplace(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)
        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/kf/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 replaceRoseResource(d_dir):
    for dirpath, dirnames, filenames in os.walk(d_dir):
        if r'com\wm\shh\zx' in dirpath:
            for smali_file in filenames:
                smali_file_path = os.path.join(dirpath, smali_file)
                print(smali_file_path)
                findRSmaliAndReplace(smali_file_path, r_regex_str)
        if r'com\wanmei\zhuxian' in dirpath and 'GameActivity.smali' in filenames:
            smali_file_path = os.path.join(dirpath, "GameActivity.smali")
            print(smali_file_path)
            findRSmaliAndReplace(smali_file_path, r_regex_str)

        if r'com\wanmei\zhuxian\qcloud\image' in dirpath and 'UpLoadImageActivity.smali' in filenames:
            smali_file_path = os.path.join(dirpath, "UpLoadImageActivity.smali")
            print(smali_file_path)
            findRSmaliAndReplace(smali_file_path, r_regex_str)

def isNeedReplaceApplicationLine(line):
    return '.super Landroid/app/Application;' in line \
           or 'invoke-direct {p0}, Landroid/app/Application;-><init>()V' in line \
           or 'invoke-super {p0, p1}, Landroid/app/Application;->attachBaseContext(Landroid/content/Context;)V' in line \
           or 'invoke-super {p0, p1}, Landroid/app/Application;->onConfigurationChanged(Landroid/content/res/Configuration;)V' in line \
           or 'invoke-super {p0}, Landroid/app/Application;->onLowMemory()V' in line \
           or 'invoke-super {p0}, Landroid/app/Application;->onTerminate()V' in line \
           or 'invoke-super {p0, p1}, Landroid/app/Application;->onTrimMemory(I)V' in line \
           or 'invoke-super {p0}, Landroid/app/Application;->onCreate()V' in line

def is_kf_replace_application(line):
    return '.super Lcom/kf/framework/KFApplication;' in line \
           or 'invoke-direct {p0}, Lcom/kf/framework/KFApplication;-><init>()V' in line \
           or 'invoke-super {p0, p1}, Lcom/kf/framework/KFApplication;->attachBaseContext(Landroid/content/Context;)V' in line \
           or 'invoke-super {p0, p1}, Lcom/kf/framework/KFApplication;->onConfigurationChanged(Landroid/content/res/Configuration;)V' in line \
           or 'invoke-super {p0}, Lcom/kf/framework/KFApplication;->onLowMemory()V' in line \
           or 'invoke-super {p0}, Lcom/kf/framework/KFApplication;->onTerminate()V' in line \
           or 'invoke-super {p0, p1}, Lcom/kf/framework/KFApplication;->onTrimMemory(I)V' in line \
           or 'invoke-super {p0}, Lcom/kf/framework/KFApplication;->onCreate()V' in line

def replace_application_verify_xmy_bug(decompile_dir):
    for dirpath, dirnames, filenames in os.walk(decompile_dir):
        if r'com\pwrd\onesdk\onesdkcommon\onesdkapplication' in dirpath and 'OneSDKApplication.smali' in filenames:
            application_path = os.path.join(dirpath, "OneSDKApplication.smali")
            print(application_path)
            with open(application_path, "r") as f:
                smali_str_arr = f.readlines()
                for line in smali_str_arr:
                    if not is_kf_replace_application(line) and 'Lcom/kf/framework/KFApplication' in line:
                        smali_str_arr[smali_str_arr.index(line)] = line.replace('Lcom/kf/framework/KFApplication',
                                                                                'Landroid/app/Application')
                    if isNeedReplaceApplicationLine(line):
                        smali_str_arr[smali_str_arr.index(line)] = line.replace('Landroid/app/Application',
                                                                                'Lcom/kf/framework/KFApplication')
            with open(application_path, "w") as f:
                f.write(''.join(smali_str_arr))


def meta_constructor(loader, node):
    value = loader.construct_mapping(node)
    return value


def script_last(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    logging.info('game_pack_info: ' + str(channel_sdk_info))
    replace_application_verify_xmy_bug(extract_dir)
    replaceRoseResource(extract_dir)
    # 冰狐渠道id 521
    # 遥望渠道id 412
    # 齐齐乐渠道id 234
    # 小绵羊渠道id 549
    # 233渠道id 535
    # 天天玩渠道id 558
    # 坚果id 413
    # 小七手游id 389
    # 游戏fan id 380
    # 零玩 id 579
    if channel_sdk_info['SDKName'] == '2lyx' or channel_sdk_info['SDKName'] == 'lcsygame':
        change_targetSdkVersion(extract_dir)


def change_targetSdkVersion(dir_path):
    yml_file = os.path.join(dir_path,'apktool.yml')
    if not os.path.exists(yml_file):
        logging.info(yml_file+'is not exist')
        return
    with open(yml_file,'r') as f:
        yaml.add_constructor(u'tag:yaml.org,2002:brut.androlib.meta.MetaInfo', meta_constructor)
        d = yaml.load(f)
        print d
        sdkInfo = d.get('sdkInfo',{})
        sdkInfo.update({'targetSdkVersion':'22'})
        print d
    with open(yml_file,'w') as fl:
        fl.write(yaml.dump(d))


if __name__ == '__main__':
    change_targetSdkVersion('C:\\Users\\Administrator\\Desktop\\xmy')