"""
修改文件名
"""
from ObjectiveC import oc_util
import os, random, re
from ObjectiveC import oc_yaml
from ObjectiveC import oc_tool

def modify_oc_file_name():
    path = oc_util.path_mix_project
    rename_file(path)
    replace_file_content(path)

def rename_file(path):
    # 打印path 和 oc_yaml.list_support_file_type
    ignore_log_manager = oc_tool.get_ignore_log_manager()
    file_log_manager = get_log_file_manager()
    for root, dirs, files in os.walk(path, topdown=True):
        dirs[:] = [d for d in dirs if isTrue(d)]
        files[:] = [f for f in files if f not in oc_yaml.list_file_not_change]
        for name in files:
            if name == oc_util.new_project_name+'.h' or name == oc_util.new_project_name+'.m':
                continue
            name_list = os.path.splitext(name)
            if name_list[1] not in oc_yaml.list_support_file_type:
                continue
            new_name = ''
            if name.count('+') == 0:
                if len(random_one_file_name(name_list[0], ignore_log_manager)) == 0:
                    continue
                new_name = new_name + random_one_file_name(name_list[0], ignore_log_manager) + name_list[1]
                old_path = os.path.join(root, name)
                new_path = os.path.join(root, new_name)
                os.rename(old_path, new_path)
                file_log_manager.write('原文件名:%s 被修改为:%s\n'%(name.ljust(40,' '), new_name))
            if name.count('+') == 1:
                a_list = name_list[0].split('+')
                first_name = a_list[0]
                second_name = a_list[1]

                new_first_name = random_one_file_name(first_name, ignore_log_manager)
                new_second_name = random_one_file_name(second_name, ignore_log_manager)
                if len(new_first_name)==0 and len(new_second_name)==0:
                    continue
                if len(new_first_name) == 0:
                    new_first_name = first_name
                if len(new_second_name)==0:
                    new_second_name = second_name
                
                new_name = new_first_name + '+' + new_second_name + name_list[1]
                old_path = os.path.join(root, name)
                new_path = os.path.join(root, new_name)
                os.rename(old_path, new_path)
                file_log_manager.write('原文件名:%s 被修改为:%s\n'%(name.ljust(40,' '), new_name))
def replace_file_content(path):
    for root, dirs, files in os.walk(path, topdown=True):
        # 排除framework
        dirs[:] = [d for d in dirs if (d.endswith('.framework')==False)]
        for name in files:
            name_list = os.path.splitext(name)
            if name_list[1] in oc_yaml.list_support_file_type:
                file_path = os.path.join(root, name)
                for index in range(len(oc_util.class_oc_file.file_name_old_list)):
                    old_text = oc_util.class_oc_file.file_name_old_list[index]
                    new_text = oc_util.class_oc_file.file_name_new_list[index]
                    with open(file_path, "r") as f:
                        file_content = f.read()
                        # 判断修改的关键词是否存在当前文件中
                        if old_text not in file_content:
                            continue
                        file_content = content_replace(file_content, old_text, new_text)
                    with open(file_path, "w") as f:
                        f.write(file_content)
            if (name=='project.pbxproj'):
                file_path = os.path.join(root, name)
                for index in range(len(oc_util.class_oc_file.file_name_old_list)):
                    old_text = oc_util.class_oc_file.file_name_old_list[index]
                    new_text = oc_util.class_oc_file.file_name_new_list[index]
                    with open(file_path, "r") as f:
                        file_content = f.read()
                        
                        # TODO:ZHMBO
                        file_content = content_replace(file_content, old_text, new_text)
                        file_content = content_replace(file_content, 'lib'+old_text, 'lib'+new_text)
                        file_content = content_replace(file_content, old_text+'.h', new_text+'.h')

                        # for h in oc_yaml.list_support_file_type:
                        #     file_content = content_replace(file_content, old_text+h, new_text+h)
                        file_content = content_replace(file_content, old_text+'+', new_text+'+')
                    with open(file_path, "w") as f:
                        f.write(file_content)
def content_replace(file_content, old_text, new_text):
    p1 = re.compile(r'[^a-zA-Z0-9_]%s[^a-zA-Z0-9_]'%old_text, re.S)
    a_list = p1.findall(file_content)
    file_new_content = file_content
    for a in a_list:
        newA = a.replace(old_text, new_text)
        file_new_content = file_new_content.replace(a, newA)
    # 开头 
    if file_new_content.startswith(old_text):
        if (file_new_content[len(old_text)].encode('UTF-8').isalpha() == False) and (file_new_content[len(old_text)].isdigit() == False) and (file_new_content[len(old_text) != '_']):
            name = file_new_content[:(len(old_text)+1)]
            newName = name.replace(old_text, new_text)
            file_new_content = file_new_content.replace(name, newName, 1)
    # 结尾
    if file_new_content.endswith(old_text):
        if (file_new_content[-1-len(old_text)].encode('UTF-8').isalpha() == False) and (file_new_content[-1-len(old_text)].isdigit() == False) and (file_new_content[-1-len(old_text)] != '_'):
            name = file_new_content[(len(file_new_content)-len(old_text)-1):]
            newName = name.replace(old_text, new_text)
            compileRegex = re.compile(r'%s$'%name)
            file_new_content = compileRegex.sub(newName, file_new_content)
    return file_new_content
def get_log_file_manager():
    return open(oc_util.path_mix + '/文件名混淆日志.txt', 'w')
def isTrue(d):
    # my_list = ['.framework', '.lproj', '.bundle', '.Bundle', '.xcassets', '.appiconset']
    #TODO:ZHMBO
    my_list = ['.framework', '.lproj', '.xcassets', '.appiconset']
    d_list = os.path.splitext(d)
    # 排除指定文件类型
    a1 = True if d_list[1] not in my_list else False
    # 排除工程名称
    a2 = (d!=(oc_util.name_current_project+'.xcodeproj'))
    # 排除忽略文件夹
    a3 = d not in list(oc_yaml.list_folder_ignore_all)
    return a1 and a2 and a3

def random_one_file_name(old_name, log_manager):
    ''' 随机一个文件名 '''
    if old_name in oc_util.class_oc_file.file_name_old_list:
        index = oc_util.class_oc_file.file_name_old_list.index(old_name)
        return oc_util.class_oc_file.file_name_new_list[index]
    if old_name in oc_util.list_ignore_keyword:
        return ''
    if old_name in oc_util.list_system_framework_word:
        log_manager.write('文件-系统framework包含关键词:%s\n'%old_name)
        oc_util.list_ignore_keyword.append(old_name)
        return ''
    if old_name in oc_util.list_project_framework_word:
        log_manager.write('文件-工程framework包含关键词:%s\n'%old_name)
        oc_util.list_ignore_keyword.append(old_name)
        return ''
    if old_name in oc_yaml.list_user_custom_keyword_not_change:
        log_manager.write('文件-用户白名单含关键词:%s\n'%old_name)
        oc_util.list_ignore_keyword.append(old_name)
        return ''
    if (old_name in oc_util.list_string_words) and (old_name not in oc_yaml.list_user_arrow_change_keyword):
        log_manager.write('文件-字符串含关键词:%s\n'%old_name)
        oc_util.list_ignore_keyword.append(old_name)
        return ''
    if old_name in oc_util.class_oc_file.total_words:
        log_manager.write('文件-OCFileInfo总表含关键词:%s\n'%old_name)
        return ''
    new_name = oc_util.prefix_file
    keep_word = ''
    for word in oc_yaml.list_keep_word:
        if old_name.endswith(word):
            keep_word = word
            break
    count = len(old_name) - len(keep_word) - len(oc_util.prefix_file)
    new_name = new_name + random_name(count) + keep_word
    # 如果文件名重复
    if new_name in oc_util.class_oc_file.file_name_new_list:
        return random_one_file_name(old_name, log_manager)
    # 如果文件名和系统framework某字段重复
    if new_name in oc_util.list_system_framework_word:
        return random_one_file_name(old_name, log_manager)
    # 如果文件名和工程framework某字段重复
    if new_name in oc_util.list_project_framework_word:
        return random_one_file_name(old_name, log_manager)
    # 如果文件名和已存在新的总表中
    if new_name in oc_util.class_oc_file.total_words:
        return random_one_file_name(old_name, log_manager)
    # 如果新文件名 和 旧文件名重复
    if new_name in oc_util.class_oc_file.all_file_name_list:
        return random_one_file_name(old_name, log_manager)
    # 加入对应的文件名列表中 
    oc_util.class_oc_file.file_name_new_list.append(new_name)
    oc_util.class_oc_file.file_name_old_list.append(old_name)
    # 文件名加入总表中
    oc_util.class_oc_file.total_words.append(new_name)
    oc_util.class_oc_file.total_words.append(old_name)
    # 修改文件名总表
    oc_util.class_oc_file.all_file_name_list.append(new_name)
    return new_name
def random_name(num):
    if num <= 3:
        numList = ['3']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 4:
        numList = ['4']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 5:
        numList = ['5']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 6:
        numList = ['6','33']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 7:
        numList = ['7','34','43']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 8:
        # (8)(3,5)(5,3)(4,4)
        numList = ['8','53','35','44']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 9:
        # (9)(6,3)(3,6)(5,4)(4,5)
        numList = ['9','63','36','54','45']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 10:
        numList = ['73','37','46','64','55','433','343','334']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 11: 
        numList = ['83','38','47','74','56','65','335','353','533','443','434','344']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 12:
        numList = ['93','39','84','48','75','57','66','336','363','633','345','354','543','534','435','453']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 13:
        numList = ['94','49','85','58','67','76','445','454','544','355','535','553','337','373','3433','4333','3343','3334']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num == 14:
        numList = ['95','59','68','86','77','455','545','554','446','464','644','3344','3434','3443','4433','4343','4334','3335','3353','3533','5333']
        str_num = random.choice(numList)
        return get_unique_string(str_num)
    elif num>=15 and num<20:
        str_num = ''
        aList = ['3','4','5','6','7','8','9']
        for _ in range(5):
            str_num = str_num + random.choice(aList)
        return get_unique_string(str_num)
    elif num>=20 and num<30:
        str_num = ''
        aList = ['3','4','5','6','7','8','9']
        for _ in range(6):
            str_num = str_num + random.choice(aList)
        return get_unique_string(str_num)
    elif num>=30 and num<40:
        str_num = ''
        aList = ['3','4','5','6','7','8','9']
        for _ in range(7):
            str_num = str_num + random.choice(aList)
        return get_unique_string(str_num)
    elif num>=40 and num<50:
        str_num = ''
        aList = ['3','4','5','6','7','8','9']
        for _ in range(8):
            str_num = str_num + random.choice(aList)
        return get_unique_string(str_num)
    else:
        str_num = ''
        aList = ['3','4','5','6','7','8','9']
        for _ in range(9,12):
            str_num = str_num + random.choice(aList)
        return get_unique_string(str_num)
def get_unique_string(num_string):
    name = ''
    for num in num_string:
        if num == '3':
            name = name + oc_util.three().capitalize()
        elif num == '4':
            name = name + oc_util.four().capitalize()
        elif num == '5':
            name = name + oc_util.five().capitalize()
        elif num == '6':
            name = name + oc_util.six().capitalize()
        elif num == '7':
            name = name + oc_util.seven().capitalize()
        elif num == '8':
            name = name + oc_util.eight().capitalize()
        elif num == '9':
            name = name + oc_util.nine().capitalize()
    return name