import json, time, ConfigParser
from copy import deepcopy

# HAR Message Watcher
# Look for changes in the HAR message file
# jdalbey  2022.9.2
idList = []    # list of CMS ID's
prevList = []  # previous messages
currList = []  # current messages
locationMap = {} # map of HAR ID's to locations
filepath = "webapps/dynamicdata" # default during development

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

# Read the har message file
def readFile():
    global filepath
    with open (filepath+"/har_messages.json",'r') as myfile:
          jsonData=myfile.read()
 
    return json.loads(jsonData)['data']

# Read the static file of cms locations and create a lookup map
def loadLocations():
     with open ("webapps/cptms/data_layers/har_locations_D12.gjson",'r') as myfile:
          jsonData=myfile.read()
 
     list = json.loads(jsonData)['features']
     # add each item to a lookup map
     for item in list:
          locationMap [item['id']] = item['properties']['location'] + " " + item['properties']['street']
     
# Setup the ID list and initialize the previous messages to empty
def initialize():
     loadLocations()
     msgList = readFile()
     global prevList, idList
     for idx in range(0,len(msgList)):
          idList.append(msgList[idx]['har']['index'])
          prevList.append("")
     return msgList

# Extract the current messages into a list
def extractMessages(msgList):
     global currList
     currList = []
     for idx in range(0,len(msgList)):
          aMessage = msgList[idx]['har']['message']['phase1']['Line1']
          currList.append(aMessage.replace("\n"," ").strip())

def setup(dir):
    global filepath
    # get path to input file from configuration
    config = ConfigParser.ConfigParser()
    config.read(dir+'/logging_service.cfg')
    filepath  = config.get('Paths', 'UnifiedLogPath')

    extractMessages(initialize())

# compare previous messages to current messages to look for changes
def getLogEntries():
     global prevList, currList
     msgList = readFile()
     extractMessages(msgList)
     size = len(currList)
     
     results = []
     # Consider each HAR message
     for idx in range(0,size):
          # Is a new message activated?
          if isEmpty(prevList[idx]) and isFull(currList[idx]):
               results.append("HAR Activated," + idList[idx] + ", '" + currList[idx] +"'")
          # Is an existing message turned off?
          if isEmpty(currList[idx]) and isFull(prevList[idx]):
               results.append("HAR Deactivated, " + idList[idx])
          # Did a message change?
          if isFull(currList[idx]) and isFull(prevList[idx]) and currList[idx] != prevList[idx]:
               results.append("HAR Updated, " + idList[idx] + ", '" + currList[idx] +"'")

     # Save the current list as previous
     prevList = deepcopy(currList)
     return results

# Local main for unit testing
def main():
     global currList
     setup("config/devlinux")
     # Loop Forever
     while True:
          # Look for changed messages
          answer = getLogEntries()
          # Output results
          for item in answer:
               print item
          # wait 
          time.sleep(5)
          # Get the current messages
          extractMessages(readFile())

if __name__ == "__main__":
     main()
     
