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

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):
    return


def script(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    return


def script_pre(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    if channel_sdk_info['id'] == "512":
        smali_classes2 = os.path.join(extract_dir, "smali_classes2/com/youkia/gamecenter")
        smali = os.path.join(extract_dir, "smali/com/youkia/gamecenter")
        if os.path.exists(smali_classes2):
            # if not os.path.exists(smali):
            #     os.mkdir(smali)
            shutil.copytree(smali_classes2, smali)
            shutil.rmtree(smali_classes2)
    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/drawable/youkia_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()


if __name__ == '__main__':
    script_pre("/tmp/ss", "E:/apk/youhua", {"id": "323"}, "", "")
    # hideSplash("/mnt/share/yanghuang/python_test/cr")
