001package jmri.implementation;
002
003import java.beans.PropertyChangeEvent;
004import java.util.ArrayList;
005import jmri.Conditional;
006import jmri.NamedBeanHandle;
007import org.slf4j.Logger;
008import org.slf4j.LoggerFactory;
009
010/**
011 * A service base class for monitoring a bound property in one of the JMRI Named
012 * beans (Turnout, Sensor, etc). For use with properties that may have more than
013 * two states where the states are represented by numbers than can be cast to
014 * integers.
015 * <p>
016 * This file is part of JMRI.
017 * <p>
018 * JMRI is free software; you can redistribute it and/or modify it under the
019 * terms of version 2 of the GNU General Public License as published by the Free
020 * Software Foundation. See the "COPYING" file for a copy of this license.
021 * <p>
022 * JMRI is distributed in the hope that it will be useful, but WITHOUT ANY
023 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
024 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
025 *
026 * @author Pete Cressman Copyright (C) 2009
027 * @since 2.5.1
028 */
029public class JmriMultiStatePropertyListener extends JmriSimplePropertyListener {
030
031    ArrayList<Integer> _states;
032
033    JmriMultiStatePropertyListener(String propName, int type, String name, Conditional.Type varType,
034            Conditional client, int state) {
035        super(propName, type, name, varType, client);
036        _states = new ArrayList<>();
037        _states.add(Integer.valueOf(state));
038    }
039
040    JmriMultiStatePropertyListener(String propName, int type, NamedBeanHandle<?> namedBean, Conditional.Type varType,
041            Conditional client, int state) {
042        super(propName, type, namedBean, varType, client);
043        _states = new ArrayList<>();
044        _states.add(Integer.valueOf(state));
045    }
046
047    public void setState(int state) {
048        _states.add(Integer.valueOf(state));
049    }
050
051    @Override
052    public void propertyChange(PropertyChangeEvent evt) {
053        log.debug("\"{}\" sent PropertyChangeEvent {}, old value =\"{}\", new value =\"{}, enabled = {}", _varName, evt.getPropertyName(), evt.getOldValue(), evt.getNewValue(), _enabled);
054        if (getPropertyName().equals(evt.getPropertyName())) {
055            int newState = ((Number) evt.getNewValue()).intValue();
056            int oldState = ((Number) evt.getOldValue()).intValue();
057            if (newState != oldState) {
058                for (int i = 0; i < _states.size(); i++) {
059                    int state = _states.get(i).intValue();
060                    if (oldState == state || newState == state) {
061                        calculateClient(i, evt);
062                    }
063                }
064            }
065        }
066    }
067    private final static Logger log = LoggerFactory.getLogger(JmriMultiStatePropertyListener.class);
068}