import argparse
import os
import re
import fnmatch

print "==========================================================================="
print "AUDIOBUS RENAME FILES AND CONTENT"
print "(c) Audiobus 2016"
print "Author: Gabriel Gatzsche"
print "Renames Files, Folders and Contents"
print "==========================================================================="

############################################
#define jobs
fileTypes = ['*']

renames = [
        [r'ABPortType(Sender|Filter|Receiver)',  r'ABPortTypeAudio\1'],    
        [r'AB(Sender|Filter|Receiver)Port',      r'ABAudio\1Port'],    
        [r'add(Sender|Filter|Receiver)Port',     r'addAudio\1Port'],

        [r'senderPortNamed',   r'audioSenderPortNamed'],
        [r'filterPortNamed',   r'audioFilterPortNamed'],
        [r'receiverPortNamed',   r'audioReceiverPortNamed'],
        
        [r'remove(Sender|Filter|Receiver)Port',   r'removeAudio\1Port'],        
        [r'sort(Sender|Filter|Receiver)PortsUsingComparitor',   r'sortAudio\1PortsUsingComparitor'],

        [r'senderPorts',   r'audioSenderPorts'],
        [r'receiverPorts',   r'audioReceiverPorts'],
        [r'filterPorts',   r'audioFilterPorts'],
        ];

ignoreFiles = ['ABSenderPort.*', 'ABFilterPort.*', 'ABReceiverPort.*', 'ABPort.h', 'Audiobus.h', 'README.txt', '*.xcodeproj', 'ABAudiobusController.*', '*.png', '*.jpg', '*.jpeg', '*.aiff', '*.m4a', '*.caf', '*.psd', '*.sketch', '*.a', '*.zip', '*.gz', '*.xcuserstate'];

searchInHiddenFilesAndFolders = False

############################################
#define helper functions
def isIgnoreFile(filePath):
    filename = os.path.basename(filePath)
    if filename == '':
        return True;
    
    if os.path.basename(filePath) == os.path.basename(__file__):
        return True;    
    
    if not os.path.exists(filePath):
       print filePath + " not found"
       return True;
    
    if os.path.islink(filePath):
        return True;
    
    for ignorePattern in ignoreFiles:
        if fnmatch.fnmatch(filename, ignorePattern):
            return True 
        
    if not searchInHiddenFilesAndFolders:
        for pathComponent in filePath.split(os.path.sep):
            if pathComponent != '' and (pathComponent [0] == '.' and pathComponent != '.'):
                return True 
            
    return False
        
    

#parse command line arguments
parser = argparse.ArgumentParser(description='Audanika Rename ABMIDIPorts into ABMIDIPort')
parser.add_argument('srcFolder', metavar='folder', nargs='+',
                    help='The source folder where to  replace stuff.')
args = parser.parse_args()
sourceFolders = args.srcFolder

#define the process process
def process(inputFolder, fileTypes, searchInHiddenFilesAndFolders):
    
    # Check if input folder is available
    if ( not os.path.exists(inputFolder) ):
        print2('Error: The input folder "' + inputFolder + '" does not exist!')
        exit(1)
        
    # Walk through filesystem
    matchingFiles = []
    matchingFolders = []
    for root, dirnames, filenames in os.walk(inputFolder):

        if isIgnoreFile(root):
            continue 
        
        matchingFolders.append(root);
        
        for fileType in fileTypes:
            for filename in fnmatch.filter(filenames, fileType):
                # Do not search in ignore files
                path = os.path.join(root, filename)
                if not isIgnoreFile(path):
                    matchingFiles.append(path)
    
    # Replace content in files and rename files
    for filePath in matchingFiles:
        
        # Replace content
        try:
            file = open(filePath,'r')
        except:
            continue        
        
        fileData = file.read() 
        file.close()
        
        fileDataOut = fileData
        for search, replace in renames:
            fileDataOut = re.sub(search, replace, fileDataOut)
        
        if fileDataOut != fileData:
            print filePath
            file = open(filePath,'w')
            file.write(fileDataOut)
            file.close()


for sourceFolder in sourceFolders:
    os.chdir(sourceFolder)
    process(sourceFolder, fileTypes, searchInHiddenFilesAndFolders)


print 'Successful'


