001package jmri.jmrit.operations.automation.actions;
002
003import java.beans.PropertyChangeEvent;
004import java.beans.PropertyChangeListener;
005import jmri.jmrit.operations.setup.Control;
006import jmri.jmrit.operations.trains.Train;
007import org.slf4j.Logger;
008import org.slf4j.LoggerFactory;
009
010public class WaitTrainTerminatedAction extends Action implements PropertyChangeListener {
011
012    private static final int _code = ActionCodes.WAIT_FOR_TRAIN_TERMINATE;
013
014    @Override
015    public int getCode() {
016        return _code;
017    }
018
019    @Override
020    public String getName() {
021        return Bundle.getMessage("WaitForTrainToTerminate");
022    }
023
024    @Override
025    public boolean isConcurrentAction() {
026        return true;
027    }
028
029    @Override
030    public void doAction() {
031        if (getAutomationItem() != null) {
032            Train train = getAutomationItem().getTrain();
033            if (train != null && train.getRoute() != null) {
034                setRunning(true);
035                train.addPropertyChangeListener(this);
036            } else {
037                finishAction(false);
038            }
039        }
040    }
041
042    /**
043     * Wait for train to terminate or if user deselects the train build
044     * checkbox.
045     *
046     */
047    private void trainUpdate(PropertyChangeEvent evt) {
048        if (getAutomationItem() != null) {
049            Train train = getAutomationItem().getTrain();
050            if ((evt.getPropertyName().equals(Train.BUILT_CHANGED_PROPERTY)
051                    && train.getStatusCode() == Train.CODE_TERMINATED) ||
052                    (evt.getPropertyName().equals(Train.BUILD_CHANGED_PROPERTY)
053                    && (boolean) evt.getNewValue() == false)) {
054                train.removePropertyChangeListener(this);
055                finishAction(true);
056            }
057        }
058    }
059
060    @Override
061    public void cancelAction() {
062        if (getAutomationItem() != null) {
063            setRunning(false);
064            Train train = getAutomationItem().getTrain();
065            if (train != null) {
066                train.removePropertyChangeListener(this);
067            }
068        }
069    }
070
071    @Override
072    public void propertyChange(PropertyChangeEvent evt) {
073        if (Control.SHOW_PROPERTY)
074            log.debug("Property change AutomationItem {}: ({}) old: ({}) new: ({})", getAutomationItem().getId(),
075                    evt.getPropertyName(), evt.getOldValue(), evt.getNewValue());
076        trainUpdate(evt);
077    }
078
079    private final static Logger log = LoggerFactory.getLogger(WaitTrainTerminatedAction.class);
080
081}