# Provides an example of listening to a Reporter, and
# printing information about a piece of rolling stock
# generated by the operations code.
#
# Based on ReporterFormater.py
#
# Author: Bob Jacobsen, copyright 2006
# Author: Paul Bender, copyright 2015 
# Part of the JMRI distribution
#
# The Reporter names is hardcoded in the example near the bottom.
# Change those to something that makes sense for your layout
#

import jmri
import java
import java.beans

# First, define the listener class.  This gets messages
# from the reporter, uses the reports to look up equipment
# in the RollingStockManager, and then prints the rolling
# stock's ID and destination.
#
class ReporterOperations(java.beans.PropertyChangeListener):
  def propertyChange(self, event):
    if (event.propertyName == "currentReport") :
      # new report, format and store
      self.report = event.newValue
      if (event.newValue!=None):
         self.value = self.format(self.report)
         print self.value
    return 

  def start(self, reporterName ) :
    # connect the object to the reporter, and start to work
    jmri.InstanceManager.getDefault(jmri.ReporterManager).provideReporter(reporterName).addPropertyChangeListener(self)
    self.cm = jmri.InstanceManager.getDefault(jmri.jmrit.operations.rollingstock.cars.CarManager)
    self.em = jmri.InstanceManager.getDefault(jmri.jmrit.operations.rollingstock.engines.EngineManager)
    return

  def stop(self) :
    # Cease operation.  
    # You can call start() again if desired.
    jmri.InstanceManager.getDefault(jmri.ReporterManager).getReporter(reporterName).removePropertyChangeListener(self)
    return
    
  def format(self, inputString) :
    # First check if this is a car 
    rs = self.cm.getByRfid(inputString.toString())
    if (rs == None) :
      #not a car, see if it is an engine
      rs = self.em.getByRfid(inputString.toString())

    #check to see if this IdTag is associated with any rolling stock.
    if (rs == None) :
      result = "Unknown Rolling Stock for IdTag " + inputString.toString()
    else :
      dest = rs.getDestination()
      if (dest==None):
        dest = "No Destination"
      result = rs.toString() + " " + dest.toString()
    return (result)
    
# End of the definition of the ReporterOperations class
    
#########################################################

# Below here is an example of the use of this class.
# Modify if to use names appropriate for your layout.
m = ReporterOperations()
m.start("FR1")
# To stop this, you can later say
# m.stop()
