001package jmri.jmrix.openlcb.swing;
002
003import jmri.util.swing.JmriJOptionPane;
004import jmri.util.JmriJFrame;
005
006import java.awt.event.WindowEvent;
007
008import org.openlcb.NodeID;
009import org.openlcb.OlcbInterface;
010
011/** 
012 * Single static method to handle dropping
013 * the CDI cache for a node.
014 *
015 * Finds all open CDI windows and closes them
016 *   with a prompt as to whether to cancel or not
017 * Then drops the CDI
018 */
019 
020public class DropCdiCache {
021
022    public static void drop(NodeID destNodeID, OlcbInterface iface) {
023        // close relevant frames
024        boolean first = true;
025        var frames = JmriJFrame.getFrameList();
026        for (var frame : frames) {
027            log.trace("frame: {} type:{}", frame, frame.getClass());
028            if (frame instanceof NodeSpecificFrame) {
029                if ( ((NodeSpecificFrame)frame).getNodeID().equals(destNodeID)) {
030                    // This window references the node and should be closed
031                    
032                    // Notify the user to handle any prompts before continuing.
033                    if (first) {
034                        int decision = JmriJOptionPane.showConfirmDialog(null, 
035                            Bundle.getMessage("OpenWindowMessage"),
036                            "Close CDI Window?",
037                            JmriJOptionPane.OK_CANCEL_OPTION
038                        );
039                        
040                        if (decision == JmriJOptionPane.CANCEL_OPTION) return;  // don't clear cache
041                        
042                        first = false;
043                        
044                    }
045                    
046                    // Close the window - force onto the queue before a possible next modal dialog
047                    jmri.util.ThreadingUtil.runOnGUI(() -> {
048                        frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
049                    });
050                    
051                    // Depending on the state of the window, and how the user handles
052                    // a prompt to discard changes or cancel, the window might 
053                    // still be open.  If so, don't clear the cache.
054                    if (JmriJFrame.getFrameList().contains(frame)) {return;}
055                }
056            }
057        }
058
059        // de-cache CDI information so next window opening will reload
060        iface.dropConfigForNode(destNodeID);
061    }
062
063    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(DropCdiCache.class);
064}