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
configdir = "config"  # default dir for production

def setup(dir):
    global lastLineNum, configdir
    lastLineNum = 0
    configdir = dir
    return

# Retrieve new messages from CAD comment log 
def getLogEntries():
    global lastLineNum, configdir
    # get path to input file from configuration
    config = ConfigParser.ConfigParser()
    config.read(configdir+'/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' - could be system was restarted or
            # this is a read sync problem: Don't modify lastLineNum
            print pathToLog + " missing, skipping file read."
            #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
            # because once the file is synced it will have same # of lines.
            print pathToLog+" is empty, skipping file read."
            #lastLineNum = 0   #Start over
            return []
        else: # file is good, read it.
            msgList = text_file.read().strip().split('\n')
            text_file.close()
            currList = []
            # If the system restarted there is usually fewer lines in the file
            # than lastLineNum, so assume all lines are new and reset lastLineNum
            if len(msgList) < lastLineNum:
                print pathToLog + " has few lines than expected, assuming restart."
                lastLineNum = 0
            currList = msgList[lastLineNum:] # new items since last file read
            lastLineNum = len(msgList)
            return currList

# Local main for unit testing
def main():
    setup("config/devlinux")
    # 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()
