# coding:utf8

__author__ = 'dong'

import os
import logging
import xml.dom.minidom
import re
import shutil
import glob
from xml.etree.ElementTree import ElementTree, Element
import distutils.dir_util
import gw_file_system
import gw_data_center

change_map = {
    "invoke-virtual {v0}, Lcom/kf/framework/KFApplication;->onCreate()V": "invoke-virtual {v0}, Landroid/app/Application;->onCreate()V",
    "invoke-virtual {v0}, Lcom/kf/framework/KFApplication;->onLowMemory()V": "invoke-virtual {v0}, Landroid/app/Application;->onLowMemory()V",
    "invoke-virtual {v0}, Lcom/kf/framework/KFApplication;->onTerminate()V": "invoke-virtual {v0}, Landroid/app/Application;->onTerminate()V",
    "invoke-virtual {v0, p1}, Lcom/kf/framework/KFApplication;->onConfigurationChanged(Landroid/content/res/Configuration;)V": "invoke-virtual {v0, p1}, Landroid/app/Application;->onConfigurationChanged(Landroid/content/res/Configuration;)V",
    "invoke-virtual {v0, p1}, Lcom/kf/framework/KFApplication;->onTrimMemory(I)V": "invoke-virtual {v0, p1}, Landroid/app/Application;->onTrimMemory(I)V", }


def replace_super_application(decompileDir):
    smali_files = glob.glob(
        os.path.join(decompileDir, 'smali*/ourpalm/android/channels/Info/Ourpalm_Channels_Application.smali'))
    if len(smali_files) == 1:
        game_application_file = smali_files[0]
        print game_application_file
        if os.path.isfile(game_application_file):
            with open(game_application_file, "r+") as f:
                file_str = f.read()
                for k, v in change_map.items():
                    file_str = file_str.replace(k, v)
            with open(game_application_file, "w+") as f:
                f.write(file_str)


def script_last(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    logging.info('------------channelSdkInfo:' + str(channelSdkInfo))
    if channelSdkInfo['SDKName'] == 'reverseforkupai':
        replace_super_application(decompileDir)

    sdk_id = channelSdkInfo['id']
    if sdk_id == "549":
        s1 = os.path.join(decompileDir, "smali_classes3/androidx")
        if not os.path.exists(s1):
            return
        smali_classes2_dir = create_mutil_smali(decompileDir)
        s3 = os.path.join(smali_classes2_dir, "androidx")
        list_package = ["arch", "collection", "core", "customview", "drawerlayout", "interpolator", "lifecycle",
                        "localbroadcastmanager", "multidex", "asynclayoutinflater", "coordinatorlayout",
                        "cursoradapter", "documentfile", "fragment", "legacy", "loader", "media"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)


def move_package(s1, s3, list_package):
    for d in list_package:
        src = os.path.join(s1, d)
        if os.path.exists(src):
            dst = os.path.join(s3, d)
            distutils.dir_util.copy_tree(src, dst)
            distutils.dir_util.remove_tree(src)


def create_mutil_smali(decompileDir):
    f_idx = 2
    while True:
        tmp = gw_file_system.get_full_path(os.path.join(decompileDir, 'smali_classes%d' % f_idx))
        tmp = tmp.replace('\\', '/')
        tmp = re.sub('/+', '/', tmp)

        if os.path.exists(tmp):
            files = os.listdir(tmp)
            if len(files) == 0:
                smali_classes2_dir = tmp
                break
            f_idx += 1
        else:
            smali_classes2_dir = tmp
            break
    # endwhile
    if not os.path.exists(smali_classes2_dir):
        os.mkdir(smali_classes2_dir)
    return smali_classes2_dir


if __name__ == '__main__':
    replace_super_application("D:\\work\\yqcr")
