import cms_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():
    # List of the available plugin modules 
    plugins = ["cms_watcher"]
    #FOR each plugin LOOP
    for plugin in plugins:
        # dynamically load the setup function for this plugin
        plugmodule = locals()[plugin]
        setupfunc = getattr(plugmodule, 'setup')
        #Call setup
        setupfunc()
    #END LOOP
    
    #DO Forever
    while True:
    #    Get simulation time
        timeStamp = getSimTime()
    #    Reset Output Buffer
        output = ""
    #    FOR each plugin LOOP
        for plugin in plugins:
            # dynamically load the setup function for this plugin
            plugmodule = locals()[plugin]
            comparefunc = getattr(plugmodule, 'compare')
            
    #        Run the plugin process returning new log entries
            results = comparefunc()          # Look for changed messages
    #    END LOOP
    #    Append simulation time and the log entries to the Output Buffer
        for item in results:
            output += timeStamp + " " + item + "\n"
    #    IF the Output Buffer has any contents THEN
        if len(output) > 0:
    #       Write (append) Output Buffer to unified log file 
            print output
    #    END IF
    #    Wait one second
        time.sleep(1)

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