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