import json, time
from copy import deepcopy

# CMS Message Watcher
# Look for changes in the CMS message file
# jdalbey  7/6/2019
idList = []    # list of CMS ID's
prevList = []  # previous messages
currList = []  # current messages
locationMap = {} # map of CMS ID's to locations

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

# Read the cms message file
def readFile():     
     with open ("webapps/dynamicdata/cms_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/cms_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]['cms']['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)):
          currList.append(
                    msgList[idx]['cms']['message']['phase1']['Line1'] + ':' + 
                    msgList[idx]['cms']['message']['phase1']['Line2'] + ':' +
                    msgList[idx]['cms']['message']['phase1']['Line3'] + ':' +
                    msgList[idx]['cms']['message']['phase2']['Line1'] + ':' +
                    msgList[idx]['cms']['message']['phase2']['Line2'] + ':' +
                    msgList[idx]['cms']['message']['phase2']['Line3'])

def setup():
     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 CMS message
     for idx in range(0,size):
          # Is a new message activated?
          if isEmpty(prevList[idx]) and isFull(currList[idx]):
               results.append("CMS Activated," + locationMap[idList[idx]] + ", '" + currList[idx] +"'")
          # Is an existing message turned off?
          if isEmpty(currList[idx]) and isFull(prevList[idx]):
               results.append("CMS Deactivated, " + locationMap[idList[idx]])
          # Did a message change?
          if isFull(currList[idx]) and isFull(prevList[idx]) and currList[idx] != prevList[idx]:
               results.append("CMS Updated, " + locationMap[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()
     # 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()
     
