001package jmri.jmrit.tracker;
002
003import jmri.Block;
004import jmri.Memory;
005import jmri.NamedBeanHandle;
006
007/**
008 * Tracks train into memory object
009 *
010 * @author Bob Jacobsen Copyright (C) 2006
011 */
012public class MemoryTracker {
013
014    /**
015     * Create a Tracker object, providing a list of blocks to watch
016     * @param b block to track.
017     * @param namePrefix system name prefix.
018     */
019    public MemoryTracker(Block b, String namePrefix) throws IllegalArgumentException {
020        block = b;
021
022        // make sure Memory objects exist & remember it
023        Memory m = jmri.InstanceManager.memoryManagerInstance()
024                .provideMemory(namePrefix + block.getSystemName());
025        namedMemory = jmri.InstanceManager.getDefault(jmri.NamedBeanHandleManager.class)
026            .getNamedBeanHandle(namePrefix + block.getSystemName(), m);
027        // set listener in the block
028        block.addPropertyChangeListener( e -> handleChange());
029
030        // first update
031        handleChange();
032    }
033
034    private void handleChange() {
035        if (log.isDebugEnabled() && (block.getValue() != null)) {
036            log.debug("set value {} in block {}", block.getValue(), block.getSystemName());
037        }
038        Object o = block.getValue();
039        if (o != null) {
040            o = o.toString();
041        }
042        namedMemory.getBean().setValue(o);
043    }
044
045    private final NamedBeanHandle<Memory> namedMemory;
046    private final Block block;
047
048    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MemoryTracker.class);
049}