import sys, cms_watcher, har_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  "%02d:%02d:%02d" % (h, m, s)    
    
# Load the sim time file and extract the seconds */
def getSimTime(path):
    global seconds    
    with open (path+"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)

# Entry point
# @param list of command line arguments
#        can provide name of config directory to use
def startup(args):
    configdir = "config"  # default dir for production
    # See if a config dir was given on command line
    if len(args) == 2:
        configdir = args[1]

    # get path to output file from configuration
    config = ConfigParser.ConfigParser()
    config.read(configdir + '/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","har_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(configdir)
    #END LOOP
    
    #DO Forever
    while True:
    #    Get simulation time
        timeStamp = getSimTime(logfilepath)
    #    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

# Entry point for application
if __name__ == '__main__':
    startup(sys.argv)
