# 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
import gw_apk_tool

asserts_dex = "39285EFA.dex"
assets_jar = "bdxadsdk.jar"


def script_init(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    sdk_id = channelSdkInfo['id']
    # if sdk_id == "584":
    gw_data_center.pack_small = False
    # gw_apk_tool.__apk_tool__ = 'apktool_2.3.4.jar'
    gw_apk_tool.__apk_tool__ = 'apktool_2.4.1.jar'


def script_first(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    return


def script(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    # logging.info('------------SDK:'+SDK)
    # logging.info('------------decompileDir:'+decompileDir)
    # logging.info('------------channelSdkInfo:'+str(channelSdkInfo))
    # logging.info('------------new_game_channel_info:'+str(new_game_channel_info))
    # logging.info('------------gameInfo:'+str(gameInfo))
    # logging.info("------rm baidu smali------")
    # restdir = decompileDir+"/"+"smali_classes2/com/baidu/gamesdk"
    # if os.path.exists(restdir):
    # shutil.rmtree(restdir)
    return


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


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):
            f_idx += 1
        else:
            smali_classes2_dir = tmp
            break
    # endwhile
    os.mkdir(smali_classes2_dir)
    return smali_classes2_dir


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 is_reverse_qihoo(file):
    with open(file, 'r+') as f:
        file_str = f.read()
        if 'KFSDK' in file_str:
            return True
        else:
            return False


def replace_init_code(decompileDir):
    file = os.path.join(decompileDir, 'assets/developer.properties')
    if os.path.exists(file):
        with open(file, 'r+') as f:
            cont = f.read()
            change_str = 'com.kfsdk.wake.SplashKFActivity'
            str = 'com.enigma.alliance.w.UnityPlayerActivity'
            cont = cont.replace(change_str, str)
            logging.info('replace_str: ' + cont)
        with open(file, 'w+') as tf:
            tf.write(cont)


if __name__ == '__main__':
    replace_init_code("D:\work\lyjymb")
