# coding:utf8
import os
import logging
import re
import glob
import shutil

import gw_data_center
import gw_file_system
import gw_apk_tool

import yaml

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


def script_init(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    gw_data_center.pack_small = False
    return

    # sdk_id = channel_sdk_info['id']
    # if sdk_id == "323":
    #     gw_data_center.pack_small = False
    #     logging.info('script_init: ' + str(channel_sdk_info))


def script_first(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    logging.info("-----debug exec first func-----")
    # game_apk = os.path.join(decompileDir, "game.apk")
    game_apk = decompileDir + "/../game.apk"
    if os.path.exists(game_apk):
        gw_file_system.delete_apk_file_by_aapt(game_apk, "assets/39285EFA.dex")
    logging.info("-----debug-----")


def script(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    logging.info('game_pack_info: ' + str(channel_sdk_info))
    # 逆向渠道id
    if channel_sdk_info['id'] == "323" or channel_sdk_info['id'] == "542":
        fixLifecycleMethod(extract_dir)
        hideSplash(extract_dir)
    decompileDir = extract_dir
    assets_dex = os.path.join(decompileDir, "../39285EFA.dex")
    assets_dir = os.path.join(decompileDir, "assets/39285EFA.dex")
    logging.info(assets_dex)
    logging.info(assets_dir)
    if os.path.exists(assets_dex):
        gw_file_system.copy_file(assets_dex, assets_dir)

    # gw_apk_tool.yml_remove_uncompress(extract_dir)
    del_do_not_compress(extract_dir)
    return


def script_last(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    if channel_sdk_info['id'] == "542":
        fix_float(extract_dir)
    return


def script_pre(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    logging.info('game_pack_info: ' + str(channel_sdk_info))
    if channel_sdk_info['id'] == "542":
        remove_smali(extract_dir)
        add_pay_field(extract_dir)

    return


def hideSplash(preDir):
    tfile = preDir + "/assets/bin/Data/splash.png"
    picDir = os.path.dirname(tfile)
    if not os.path.exists(picDir):
        os.makedirs(picDir)
        shutil.copyfile(os.path.dirname(os.path.abspath(__file__)) + '/FFFFFF-0.png', tfile)
    else:
        if os.path.isfile(tfile):
            shutil.copyfile(os.path.dirname(os.path.abspath(__file__)) + '/FFFFFF-0.png', tfile)
        else:
            logging.info('game_pack_info: ' + tfile + 'is not exists!')

    tfile = preDir + "/res/values/styles.xml"
    if os.path.isfile(tfile):
        with open(tfile, 'r+') as f:
            cont = f.read()
            cont = cont.replace('<item name="android:windowBackground">@drawable/youkia_splash</item>'
                                , '<item name="android:windowBackground">@color/transparent</item>')
            f.truncate(len(cont))
            f.seek(0)
            f.write(cont)
            f.close()
    else:
        logging.info('game_pack_info: ' + tfile + 'is not exists!')
    return


def intoFirstLine(target, repl, cont, superclass):
    # srcStr = "onBackPressed"
    # regexp = '.method (?:public|protected) +?'+target+"\([^.]+?\.locals +[0-9]{1,2}"
    regexp = '.method (?:public|protected) +?' + target + "\([^.]+?\.locals +([0-9]{1,2})"
    # print(regexp)
    reObj = re.compile(regexp)
    matchO = reObj.search(cont)
    if matchO:
        # print(matchO.group(0))
        methodHead = matchO.group(0)
        if matchO.group(1) == "0":
            methodHead = re.sub("locals +0", "locals 1", methodHead)

        repl = methodHead + r'\n\n    ' + repl + r'\n\n'
        cont = reObj.sub(repl, cont)
    else:
        # do call .super method
        isuper = "invoke-super {p0}, " + superclass + "->" + target + "()V"
        cont += "\n\n.method protected " + target + "()V\n    .locals 0\n\n    " + repl + "\n\n    " + isuper + "\n\n    return-void\n.end method"

    return cont


def fixLifecycleMethod(preDir):
    for tfile in glob.glob(preDir + "/" + "smali*/com/youkia/gamecenter/GameCenterActivity.smali"):
        if os.path.isfile(tfile):
            with open(tfile, 'r+') as f:
                cont = f.read()
                changes = {
                    "onPause": "invoke-static {}, Lcom/qihoo/gamecenter/sdk/matrix/Matrix;->onPause()V",
                    "onResume": "invoke-static {}, Lcom/qihoo/gamecenter/sdk/matrix/Matrix;->onResume()V",
                    "onDestroy": "invoke-static {p0}, Lcom/qihoo/gamecenter/sdk/matrix/Matrix;->destroy(Landroid/content/Context;)V",
                    "onStop": "invoke-static {}, Lcom/qihoo/gamecenter/sdk/matrix/Matrix;->onStop()V"
                }
                mas = re.search('^.super L([^;]*);?', cont, re.MULTILINE)

                superclass = ""
                if mas:
                    superclass = 'L' + mas.group(1) + ';'

                for k, v in changes.iteritems():
                    cont = intoFirstLine(k, v, cont, superclass)

                f.seek(0)
                f.truncate(len(cont))
                f.write(cont)
                f.close()


def add_pay_field(fooDir):
    for tfile in glob.glob(fooDir + "/" + "smali*/com/youkia/gamecenter/BaseMainActivity.smali"):
        print tfile
        if os.path.isfile(tfile):
            with open(tfile, 'r+') as f:
                cont = f.read()
                rrr = re.compile(r'const-string v13, \"app_order_id\"')
                endStr = rrr.findall(cont)
                if len(endStr) > 1:
                    if endStr[0] == None:
                        return
                    logging.info('替换字符串为：' + endStr[0])
                inserts = '''
    const-string v13, "app_ext_2"\n

	invoke-static {}, Lcom/kf/framework/java/KFSDKUser;->getInstance()Lcom/kf/framework/java/KFSDKUser;\n

    move-result-object v14\n

    invoke-virtual {v14}, Lcom/kf/framework/java/KFSDKUser;->getOpenId()Ljava/lang/String;\n

    move-result-object v14\n

	invoke-virtual {v3, v13, v14}, Landroid/os/Bundle;->putString(Ljava/lang/String;Ljava/lang/String;)V\n

	const-string v13, "app_order_id"'''

                if len(endStr) > 1:
                    cont = cont.replace(endStr[0], inserts)
                    f.seek(0)
                    f.write(cont)


def remove_smali(path):
    for tfile in glob.glob(path + "/" + "smali*/com/youkia/gamecenter/BaseMainActivity.smali"):
        print tfile
        logging.info('删除路径：' + tfile)
        if os.path.isfile(tfile):
            with open(tfile, 'r+') as f:
                lines = f.readlines()
                start = 0
                end = 0
                line_num = 0
                for i in lines:
                    print len(i.strip(" "))
                    print len('const-string v13, "access_token"')
                    if i.replace('\n', '').strip(" ") == 'const-string v13, "access_token"':
                        start = lines.index(i)
                        print start
                    if start > 0 and i.replace('\n', '').strip(" ") == 'const-string v13, "amount"':
                        end = line_num
                        end -= 1
                        print end
                        break
                    line_num += 1
                for i, v in enumerate(lines):
                    if i >= start and i < end:
                        lines[i] = ''
                    if i > end:
                        break

            with open(tfile, 'w') as tf:
                tf.write(''.join(lines))


def fix_float(lastDir):
    for tfile in glob.glob(lastDir + "/" + "smali*/com/qihoo/sdkplugging/host/ApkPluggingManager.smali"):
        print tfile
        if os.path.isfile(tfile):
            with open(tfile, 'r+') as f:
                cont = f.read()
                goalStr = 'invoke-virtual {v1, p1, p2, p3, p4}, Lcom/qihoo/sdkplugging/host/pluggingitem/ApkPluggingItem;->doPluggingCommandInItem(Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Object;)Ljava/lang/Object;'
                print type(goalStr)
                changes = '''
    const v2, 0xc350\n

    invoke-virtual {p3}, Ljava/lang/Integer;->intValue()I\n

    move-result v3\n

    if-eq v2, v3, :cond_f\n

    invoke-virtual {v1, p1, p2, p3, p4}, Lcom/qihoo/sdkplugging/host/pluggingitem/ApkPluggingItem;->doPluggingCommandInItem(Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Object;)Ljava/lang/Object;'''
                cont = cont.replace(goalStr, changes)
                f.seek(0)
                f.write(cont)


def del_do_not_compress(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:
        d = yaml.load(f)
        print d
        del d['doNotCompress']
        print d
    with open(yml_file, 'w') as fl:
        fl.write(yaml.dump(d))


if __name__ == '__main__':
    # remove_smali('D:\\xqnnn')
    # add_pay_field('D:\\xqnnn')
    # fix_float("D:\\test")
    # script("/tmp/ss", "/mnt/share/yanghuang/python_test/any_dir", { "id": "323" }, "", "")
    # hideSplash("/mnt/share/yanghuang/python_test/cr")
    del_do_not_compress('e:\\apk\\youhua')
