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


# Load the sim time file and extract the seconds */
def getSimTime():
    with open ("../dynamicdata/sim_elapsedtime.json", 'r') as myfile:
        jsonData=myfile.read()
         
    seconds = json.loads(jsonData)['elapsedtime']
    # convert seconds to H:MM:SS
    m, s = divmod(int(seconds), 60)
    h, m = divmod(m, 60)
    return  "%d:%02d:%02d" % (h, m, s)    

def main():
    # Delete any previously existing output file
    f = open("../dynamicdata/unifiedlog.html", "w")
    startHTML = "<HTML><HEAD><meta http-equiv=\"refresh\" content=\"5\" /></HEAD><BODY><PRE>"
    f.write(startHTML);
    f.close()            
    # List of the available plugin modules 
    plugins = ["cms_watcher","cad_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 setup 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 
            print output,
            f = open("../dynamicdata/unifiedlog.html", "a")
            f.write(output)
            f.close()            
    #    END IF
    #    Wait one second
        time.sleep(1)

#END DO
if __name__ == "__main__":
    main()