"""
混淆方法名
"""
import os, re
from ObjectiveC import oc_yaml
from ObjectiveC import oc_util

def init():
    path = oc_util.path_mix_project
    if len(oc_util.class_oc_file.method_old_list) != len(oc_util.class_oc_file.method_new_list):
        print('方法新旧列表数量不一致!!!')
        return
    mix_method(path)
    property_mix_log = open(oc_util.path_mix + "/File混淆日志" + ".txt", "a")
    for index in range(len(oc_util.class_oc_file.method_old_list)):
        old_text = oc_util.class_oc_file.method_old_list[index]
        new_text = oc_util.class_oc_file.method_new_list[index]
        property_mix_log.write('原方法名:%s 被修改为:%s\n'%(old_text.ljust(30,' '), new_text))
    property_mix_log.close()
def isTrue(d):
    return (d.endswith('.xcodeproj')==False) and (d.endswith('.framework')==False) and (d not in oc_yaml.list_folder_ignore_all)
def mix_method(path):
    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 (os.path.splitext(f)[1] in oc_yaml.list_support_open_file_type) or (f=='contents')]
        for name in files:
            file_path = os.path.join(root, name)
            with open(file_path, 'r') as f:
                file_content = f.read()
                for index in range(len(oc_util.class_oc_file.method_old_list)):
                    old_text = oc_util.class_oc_file.method_old_list[index]
                    new_text = oc_util.class_oc_file.method_new_list[index]
                    if file_content.count(old_text)>0:
                        file_content = replace_method(file_content, old_text, new_text)
            with open(file_path, 'w') as f:
                f.write(file_content)
def replace_method(file_content, old_text, new_text):
    p1 = re.compile(r'[^a-zA-Z0-9_]%s[^a-zA-Z0-9_]'%old_text)
    a_list = p1.findall(file_content)
    for a in a_list:
        b = a.replace(old_text, new_text)
        file_content = file_content.replace(a, b)
    # 开头 
    if file_content.startswith(old_text):
        if (file_content[len(old_text)].encode('UTF-8').isalpha() == False) and (file_content[len(old_text)].isdigit() == False) and (file_content[len(old_text) != '_']):
            name = file_content[:(len(old_text)+1)]
            newName = name.replace(old_text, new_text)
            file_content = file_content.replace(name, newName, 1)
    # 结尾
    if file_content.endswith(old_text):
        if (file_content[-1-len(old_text)].encode('UTF-8').isalpha() == False) and (file_content[-1-len(old_text)].isdigit() == False) and (file_content[-1-len(old_text)] != '_'):
            name = file_content[(len(file_content)-len(old_text)-1):]
            newName = name.replace(old_text, new_text)
            compileRegex = re.compile(r'%s$'%name)
            file_content = compileRegex.sub(newName, file_content)
    return file_content