# 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_data_center
import gw_file_system


def script_init(workspace_sdk_dir, extract_dir, channelSdkInfo, new_game_channel_info, game_info):
    sdk_id = channelSdkInfo['id']
    gw_data_center.pack_small = False
    return


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):
        # A3AEECD8
        gw_file_system.delete_apk_file_by_aapt(game_apk, "assets/39285EFA.dex")
    logging.info("-----debug first-----")


def script(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    dex = decompileDir + "../39285EFA.dex"
    asserts = os.path.join(decompileDir, "assets/39285EFA.dex")
    if os.path.exists(asserts) and os.path.exists(os.path.join(dex)):
        distutils.dir_util.copy_tree(dex, asserts)
    logging.info("-----debug script-----")


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


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):
    smali_files = glob.glob(os.path.join(decompileDir, 'smali*/com/qihoo/'))
    if len(smali_files) >= 1:
        iter_smali = iter(smali_files)
        while True:
            try:
                qihoo_file_path = iter_smali.next()
                file = os.path.join(qihoo_file_path, 'gamecenter/sdk/matrix/Matrix.smali')
                if os.path.exists(file):
                    logging.info('Matrix exits in %s' % qihoo_file_path)
                    if is_reverse_qihoo(file):
                        with open(file, 'r+') as f:
                            cont = f.read()
                            change_str = '0x82c'
                            str = '0x82b'
                            cont = cont.replace(change_str, str)
                            logging.info('replace_str: ' + cont)
                        with open(file, 'w+') as tf:
                            tf.write(cont)

            except StopIteration:
                break


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