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.AutomationItem; 010import jmri.jmrit.operations.setup.Control; 011 012public class DownCounterAction extends Action implements PropertyChangeListener { 013 014 private static final int _code = ActionCodes.DOWN_COUNTER; 015 int _counter = -1; 016 017 @Override 018 public int getCode() { 019 return _code; 020 } 021 022 @Override 023 public String getName() { 024 return Bundle.getMessage("DownCounter"); 025 } 026 027 @Override 028 public void doAction() { 029 if (getCount() < 1) { 030 setCount(getUserCount()); 031 } 032 decrementCounter(); 033 if (getCount() > 0) { 034 finishCounterAction(false); 035 } else { 036 finishCounterAction(true); 037 } 038 } 039 040 @Override 041 public void cancelAction() { 042 // no cancel for this action 043 } 044 045 private int getCount() { 046 return _counter; 047 } 048 049 private void setCount(int count) { 050 _counter = count; 051 } 052 053 private void decrementCounter() { 054 _counter -= 1; 055 } 056 057 private void finishCounterAction(boolean success) { 058 setRunning(true); 059 getAutomationItem().setActionSuccessful(success); 060 setRunning(false); 061 firePropertyChange(ACTION_COMPLETE_CHANGED_PROPERTY, !success, success); 062 } 063 064 private int getUserCount() { 065 int count = -1; 066 String msg = getAutomationItem().getMessage(); 067 if (!msg.isEmpty()) { 068 try { 069 count = Integer.parseInt(msg.trim()); 070 } catch (NumberFormatException nfe) { 071 log.error("Down count ({}) isn't a number", msg); 072 } 073 } 074 return count; 075 } 076 077 @Override 078 public String getStatus() { 079 if (getCount() < 0) { 080 setCount(getUserCount()); 081 getAutomationItem().addPropertyChangeListener(this); 082 } 083 if (getCount() < 0) { 084 return (Bundle.getMessage("Error")); 085 } 086 return Integer.toString(getCount()); 087 } 088 089 @Override 090 public void reset() { 091 setCount(-1); 092 } 093 094 @Override 095 public void propertyChange(PropertyChangeEvent e) { 096 if (Control.SHOW_PROPERTY) 097 log.debug("Property change: ({}) old: ({}) new: ({})", e.getPropertyName(), e.getOldValue(), e 098 .getNewValue()); 099 if (e.getPropertyName().equals(AutomationItem.AUTOMATION_ITEM_MESSAGE_CHANGED_PROPERTY)) { 100 reset(); // reset down counter value 101 } 102 } 103 104 private final static Logger log = LoggerFactory.getLogger(DownCounterAction.class); 105}