"""
删除注释 
删除打印
"""
import re, os
from ObjectiveC import oc_util
from ObjectiveC import oc_yaml

def delete_print_or_annotation(type):
    ''' 
    type=1 删除注释\n
    type=2 删除打印
    '''
    support_type = ['.h', '.m', '.mm', '.pch', '.swift']
    for root, dirs, files in os.walk(oc_util.path_mix_project, topdown=True):
        dirs[:] = [ d for d in dirs if d.endswith('.framework')==False]
        files[:] = [f for f in files if os.path.splitext(f)[1] in support_type]
        files[:] = [f for f in files if f not in oc_yaml.list_not_delete_print_or_annotation]
        for name in files:
            file_path = os.path.join(root, name)
            with open(file_path, 'r') as f:
                file_content = f.read()
                if type == 1:
                    file_content = search_annotation_and_delete(file_content)
                if type == 2:
                    file_content = search_print_and_delete(file_content)
            with open(file_path, 'w') as f:
                f.write(file_content)

def search_print_and_delete(file_content):
    ''' 找出打印并返回删除后的文件内容 '''
    p1 = re.compile(r'(NSLog\()(.*?)(;)(\n)')
    a_list = p1.findall(file_content)
    for a in a_list:
        str_a = ''.join(a)
        file_content = file_content.replace(str_a, '\n')
    return file_content
def search_annotation_and_delete(file_content):
    ''' 找出注释并返回删除后的文件内容 '''
    # /// 三斜杠注释
    p1 = re.compile(r'///(.*?)\n', re.S)
    aList = p1.findall(file_content)
    for a in aList:
        a = '///' + a + '\n'
        file_content = file_content.replace(a, '\n')
    # /**/ 移出这种注释
    p3 = re.compile(r'/\*(.*?)\*/', re.S)
    cList = p3.findall(file_content)
    for c in cList:
        c = '/*' + c + '*/'
        if c == '/*,*/':
            continue
        file_content = file_content.replace(c, '\n')
    # #pragma mark 去这种打印
    p4 = re.compile(r'#pragma mark(.*?)\n')
    dList = p4.findall(file_content)
    for d in dList:
        d = '#pragma mark' + d + '\n'
        file_content = file_content.replace(d, '\n')
    # 双斜杠加空格
    p2 = re.compile((r'// (.*?)\n'), re.S)
    bList = p2.findall(file_content)
    for b in bList:
        b = '// ' + b + '\n'
        file_content = file_content.replace(b, '\n')
    # 双斜杠加!
    p2 = re.compile((r'//!(.*?)\n'), re.S)
    bList = p2.findall(file_content)
    for b in bList:
        b = '//!' + b + '\n'
        file_content = file_content.replace(b, '\n')
    # 移出 双斜杠加换行
    file_content = file_content.replace('//\n', '\n')
    return file_content