import json, time, ConfigParser
#from copy import deepcopy

# Incident Activity log Watcher
# Look for changes in the IncidentActivity log.
# The comments from the Incident Activity log be will appended to the log 
# as they arrive from the web app.
# 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/24/2019

lastLineNum = 0

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

# Read the log 
def readFile():
    # get path to input file from configuration
    config = ConfigParser.ConfigParser()
    config.read('config/logging_service.cfg')
    logfilepath = config.get('Paths', 'ActivityLogPath')
    logfilename = "data.json"   #"IncidentActivity.log"
    data_summary = "data_summary.json"
    lines = []
    output = []
    try:
        json_file = open (logfilepath + logfilename,'r')
    except IOError:
        print "Error: missing "+logfilepath+logfilename+" file."
    else:
        jsonData=json_file.read()
        # implement ticket #192
        output = json.loads(jsonData)['data'] 
        # read in data_summary_json file
        # assuming the data_summary.json is in the trunk foldera
        data_summary = open(logfilepath + data_summary, 'r')
        summary_json = data_summary.read()
        data_lst = json.loads(summary_json)['data']
        for entry in data_lst:
            # put the first 3 entries as place holder to be consistent with other type of logging
            output.append([entry[0], entry[1] , entry[2], entry[3] , ", Incident Created, ", ""]) 
        json_file.close()
    return output
    
def setup():
    # nothing needed for setup
    return

# Retrieve new messages from activity log 
def getLogEntries():
    global lastLineNum
    msgList = readFile()
    currList = []
    currList = msgList[lastLineNum:]    # new items since last file read
    lastLineNum = len(msgList)
    resultList = []
    # Format messages into desired result format
    for item in currList:
        # implement ticket #188
        # extract desired fields
        incident_num = item[0].split("-")[1] 
        # extract the incident number from the date time field
        name = item[3].replace(',','')
        code = item[4].replace(',','')
        msg = item[5].replace(',','')
        desiredFields = "Activity Log,"+name+"," + incident_num + " " + code+" "+msg
        # Append to results list
        resultList.append(desiredFields)
    return resultList

# 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()
