# coding:utf8
import os
import logging
import shutil
from xml.etree import ElementTree as ET
import traceback
import distutils.dir_util
import re
import gw_report_tool
import gw_data_center
import gw_file_system
import gw_apk_tool

ANDROID_NS = 'http://schemas.android.com/apk/res/android'


def script_second(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    # split(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):
    # handle_same_package(extract_dir, channel_sdk_info)
    return


def script(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    # smali_classes2
    # split(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info)
    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")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir)
        list_package = ["androidx"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

    if sdk_id == "549" or sdk_id == "597":
        s1 = os.path.join(extract_dir, "smali_classes3")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir)
        list_package = ["androidx"]
        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__':
    extract_dir = 'C:/Users/Administrator/Desktop/apk/qmqjbd_8226_bb_2.3.0'
    channel_sdk_info = {'packNameSuffix': "new.package.name"}
    handle_same_package(extract_dir, channel_sdk_info)
