#name of the tests module that will be created
tModule = "allTests"

#name of the notifiers module that will be created
nModule = "allNotifiers"

#the file that contains all tests names, separated by space or newline
tList = "tests"

#the file that contains all notifiers names, separated by space or newline
nList = "notifiers"

import os, notify

"""
    words = list of the tests that the module will include
    new = file descriptor opened for writing
    
    The function creates a module that initializes a NewCheckRunner
    with all the CheckBase specified by name
    All tests extending CheckBase must be written in a file with the same
    name as the test+ ".py"
"""
def createTestsModule(words, new):   
    if words:
        function = words[0]
        new.write("from " + function + " import " + function + "\n")
        createTestsModule(words[1:], new)
        new.write("cr.add(" + function + "())\n")
    else:
        new.write("from runner import NewCheckRunner\n")
        new.write("cr = NewCheckRunner()\n")

"""
    words = list of the notifiers that the module will include
    new = file descriptor opened for writing
    
    The function creates a module that initializes the notify.notifiers
    array with the BaseNotifiers specified in the words vector
    All notifiers extendinf BaseNotifiers must be written in a file
    with the same name as the notifier + ".py"
"""        
def createNotifiersModule(words, new):
    if words:
        notifier = words[0]
        new.write("from " + notifier + " import " + notifier + "\n")
        createNotifiersModule(words[1:], new)
        new.write("notify.notifiers.append(" + notifier + "())\n")
    else:
        new.write("import notify\n")

"""
    fileName = name of file to read
    Returns an array containing all the words in the file
"""
def getWords(fileName): 
    f = open(fileName, "r")
    words = []
    linesList = f.readlines() 
    for line in linesList:
        words += line.split()
    f.close()
    return words

def run():  
    
    #creates the module that initiates the cr CheckRunner
    tNames = getWords(tList)
    new = open(tModule + ".py", "w") 
    createTestsModule(tNames, new)   
    new.close() 
    
    #creates the module that initiates the notify.notifiers array
    nNames = getWords(nList)
    new = open(nModule + ".py", "w")
    createNotifiersModule(nNames, new)
    new.close()
    
    #imports the new created module that adds all CheckBase tests to a CheckRunner: cr
    testsModule = __import__(tModule)
    
    #notify.notifiers is filled
    notifiersModule = __import__(nModule)
    
    #runs all the tests
    output = testsModule.cr.runTests();
    
    #notify the problems found
    if output:
        for (check, problem) in output:
            notify.send('%s: "%s"\n' % (check.name, problem.msg))
    
    #remove the modules used for import
    os.remove(tModule + ".py")
    os.remove(nModule + ".py")
    
if __name__ == "__main__":
    run()
    