# 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


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


def script_last(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    sdk_id = channel_sdk_info['id']
    if sdk_id == "549":
        s1 = os.path.join(extract_dir, "smali_classes2/com")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com")
        list_package = ["mcs", "mobile", "sqwan", "sy37", "sy37sdk", "twobigears", "xiaomi"]
        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__':
    script_pre("", "f:\\ztest", "", "", "")
