import json, time, ConfigParser
from copy import deepcopy

# CAD comment log Watcher
# Look for changes in the CAD comment log.
# The CADserver will append new comments to the log as they arrive 
# from clients.  We only need to keep track of the log length in order to
# determine if a new comment has been added.  We will output the 
# new messages that arrived during the last wait interval. 
# jdalbey  7/6/2019

lastLineNum = 0

# Utility functions
def isEmpty(cmsitem):
    return cmsitem == ",,,,,"
def isFull(cmsitem):
    return not isEmpty(cmsitem)

# Read the cad comments log 
def readFile():
    # get path to input file from configuration
    config = ConfigParser.ConfigParser()
    config.read('config/logging_service.cfg')
    logfilepath  = config.get('Paths', 'UnifiedLogPath')
    
    lines = []
    try:
        text_file = open(logfilepath + "CADcomments.log", "r")
    except IOError:
        print "Error: missing "+logfilepath+"CADcomments.log file."
    else:
        lines = text_file.read().split('\n')
        text_file.close()    
    return lines
    
def setup():
    lastLineNum = 0
    return

# Retrieve new messages from CAD comment log 
def getLogEntries():
    global lastLineNum
    msgList = readFile()
    currList = []
    currList = msgList[lastLineNum:]    # new items since last file read
    lastLineNum = len(msgList)-1
    return currList

# Local main for unit testing
def main():
    setup()
    # Loop Forever, checking every five seconds
    while True:
        # Look for new messages
        answer = getLogEntries()
        # Output results
        for item in answer:
            print item
        # wait 
        time.sleep(5)

if __name__ == "__main__":
    main()
