import json, time, ConfigParser, os
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)

def setup():
    lastLineNum = 0
    return

# Retrieve new messages from CAD comment log 
def getLogEntries():
    global lastLineNum
    # get path to input file from configuration
    config = ConfigParser.ConfigParser()
    config.read('config/logging_service.cfg')
    logfilepath  = config.get('Paths', 'UnifiedLogPath')
    pathToLog = logfilepath + "CADcomments.log"
    
    try:
        text_file = open(pathToLog, "r")
    except IOError as ex:
        if ex.errno == 2:
            # 'No such file or directory
            print pathToLog + " missing: assuming reset"
            lastLineNum = 0   #Start over
            return []
        else:
            print "IOError reading "+pathToLog+" file."
            print "errno: ",ex.errno
            
    else:
        # Check file size
        fileSize = os.path.getsize(pathToLog)
        if fileSize == 0:
            # Assume this is a read sync problem: Don't modify lastLineNum
            print pathToLog+" is empty."
            return []
        else: # file is good, read it.
            msgList = text_file.read().split('\n')
            text_file.close()
            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()
