import cms_watcher, cad_watcher, activitylog_watcher, time, json, ConfigParser
# Unified Logging Service
# jdalbey 7/6/2019

outputFilename = "unifiedlog.csv"
seconds = 0
# convert seconds to H:MM:SS
def toHMS(seconds):
    m, s = divmod(int(seconds), 60)
    h, m = divmod(m, 60)
    return  "%d:%02d:%02d" % (h, m, s)    
    
# Load the sim time file and extract the seconds */
def getSimTime():
    global seconds    
    with open ("webapps/dynamicdata/sim_elapsedtime.json", 'r') as myfile:
        jsonData=myfile.read()
    try:     
       seconds = json.loads(jsonData)['elapsedtime']
    except:
       print "Unable to read sim time. ",
       print "Proceeding with previous time: ", toHMS(seconds)
    # convert seconds to H:MM:SS
    return toHMS(seconds)

def startup():
    # get path to output file from configuration
    config = ConfigParser.ConfigParser()
    config.read('config/logging_service.cfg')
    logfilepath  = config.get('Paths', 'UnifiedLogPath')
    
    # Delete any previously existing output file
    f = open(logfilepath + outputFilename, "w")
    f.close()            
    # List of the available plugin modules 
    plugins = ["cms_watcher","cad_watcher","activitylog_watcher"]
    #FOR each plugin LOOP
    for plugin in plugins:
        # dynamically load the setup function for this plugin        
        plugmodule = globals()[plugin]
        setupfunc = getattr(plugmodule, 'setup')
        #Call setup
        setupfunc()
    #END LOOP
    
    #DO Forever
    while True:
    #    Get simulation time
        timeStamp = getSimTime()
    #    Reset Output Buffer
        output = ""
        results = []
    #    FOR each plugin LOOP
        for plugin in plugins:
            # dynamically load the get log function for this plugin
            plugmodule = globals()[plugin]
            getfunc = getattr(plugmodule, 'getLogEntries')
            
    #        Run the plugin process returning new log entries
            results = getfunc()     
    #       Append simulation time and the log entries to the Output Buffer
            for item in results:
                trimmed_item = item.strip()
                if len(trimmed_item) > 0:
                    output += timeStamp + ", " + trimmed_item + "\n"
    #    END LOOP
    #    IF the Output Buffer has any contents THEN
        if len(output) > 0:
    #       Write (append) Output Buffer to unified log file as CSV
    #       Assumes fields don't contain commas 
            print output,
            f = open(logfilepath + outputFilename, "a")
            f.write(output)
            f.close()            
    #    END IF
    #    Wait five seconds
        time.sleep(5)

#END DO

if __name__ == '__main__':
    startup()