<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">/*
 * AllowedModeChooser.java
 *
 * Created on Feb 12, 2010, 6:28:34 AM
 */
package usda.weru.weps.location.chooser;

import static java.awt.AWTEvent.MOUSE_EVENT_MASK;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.Map;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.event.EventListenerList;
import org.apache.log4j.Logger;
import usda.weru.weps.location.StationMode;

/**
 *
 * @author Joseph Levin &lt;joelevin@weru.ksu.edu&gt;
 */
public class AllowedStationModeChooser extends javax.swing.JPanel implements FocusListener, ActionListener {

    private static final long serialVersionUID = 1L;
    private static final Logger LOGGER = Logger.getLogger(AllowedStationModeChooser.class);
    private final Map&lt;StationMode, JCheckBox&gt; c_checkBoxes;
    private final ArrayList &lt;StationMode&gt; allowedModes;
    private final ArrayList &lt;StationMode&gt; enabledModes;
    private final EventListenerList c_listeners;
    private ArrayList&lt;String&gt; defaultsVals;
    private JComboBox&lt;String&gt; defaultList;
    private String defaultListSel;
    private final AllowedStationModeChooser chooser;
    AllowedStationModeChooserLabel dummyLabel1;
    AllowedStationModeChooserLabel dummyLabel2;
    
    public class AllowedStationModeChooserLabel extends JLabel {
        
        private static final long serialVersionUID = 1L;
        
    }
    
    public AllowedStationModeChooser() {
        chooser = this;
        c_listeners = new EventListenerList();
        allowedModes = new ArrayList &lt;&gt;();
        enabledModes = new ArrayList &lt;&gt;();
        c_checkBoxes = new EnumMap&lt;&gt;(StationMode.class);
        dummyLabel1 = new AllowedStationModeChooserLabel ();
        dummyLabel2 = new AllowedStationModeChooserLabel ();
        initComponents();
        initContents();
    }
    /**
     * The LoadProperties class loads properties from Component names.
     *  We need additional properties for this container so that they are caught
     *  in LoadProperties.  We attach them here to dummy (empty) labels.
     *  See LoadProperties.java, comp instance of AllowedStationModeChooserLabel
     * @param name - the name of this property is CD-cligen.allowedmodes or CD-windgen.allowedmodes
     *                (when used in ConfigPanel_n)
     */
    @Override
    public void setName (String name) {
        super.setName(name);
        dummyLabel1.setName(name.replace("allowed", "enabled"));
        dummyLabel2.setName(name.replace("allowedmodes", "defaultmode"));
    }

    private void initContents() {

        defaultListSel = "";
        defaultList = new JComboBox&lt;&gt;();
        defaultList.setAlignmentX(LEFT_ALIGNMENT);
        
        defaultList.addActionListener(new ActionListener () {
            @Override
            public void actionPerformed(ActionEvent e) {
                // We only care about user mouse events
                if ((e.getModifiers() &amp; MOUSE_EVENT_MASK) &gt; 0) {
//                    String sel = defaultListSel;
                    if (defaultList == null || defaultList.getSelectedItem() == null) {
                        return;
                    }
                    if (defaultListSel.length() == 0) {
                        defaultListSel = (String)defaultList.getSelectedItem();
                    } 
                    if (((String)defaultList.getSelectedItem()).contentEquals(defaultListSel)) {
                        return;
                    }
                    defaultListSel = (String)defaultList.getSelectedItem();
                    chooser.actionPerformed(e);
                }
            }
        });
        defaultsVals = new ArrayList&lt;&gt;();
        updateDefaults();
        add (new JLabel(" "));
        add (new JLabel ("default mode:"));
        add (defaultList);
        
        add (dummyLabel1);
        add (dummyLabel2);
        
        updateCheckBoxes ();
    }
    
    private void updateCheckBoxes() {
        JCheckBox box;

        for (StationMode mode : StationMode.values()) {
            if (isAllowed(mode)) {
                if (c_checkBoxes.containsKey(mode)) {
                    box = c_checkBoxes.get(mode);
                } else {
                    box = new JCheckBox(mode.getDisplayName());
                    box.setFont(getFont());
                    box.addActionListener(new ActionListener () {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            updateEnabled(e.getActionCommand());
                            updateDefaults();
                            chooser.actionPerformed(e);
                        }
                    });

                    c_checkBoxes.put(mode, box);
                    // there are 5 other components in this container besides
                    // the checkboxes. We want the checkboxes always at the top
                    // of this container
                    add(box, getComponentCount()-5);
                }
                box.setSelected(isEnabled(mode));
            }
        }
        updateDefaults();
    }
    
    private void updateEnabled (String boxName) {
        for (Map.Entry&lt;StationMode, JCheckBox&gt; entry : c_checkBoxes.entrySet()) {
            if (entry.getValue().getText().contentEquals(boxName)) {
                if (entry.getValue().isSelected()) {
                    enabledModes.add(entry.getKey());
                } else {
                    enabledModes.remove(entry.getKey());
                }
                break;
            }
        }
        checkForNoSelections (c_checkBoxes, boxName);
    }
    
    private void checkForNoSelections (Map&lt;StationMode, JCheckBox&gt; checkBoxes, String boxName) {
        boolean atLeastOne = false;
        for (Map.Entry&lt;StationMode, JCheckBox&gt; entry : checkBoxes.entrySet()) {
                if (entry.getValue().isSelected()) {
                    atLeastOne = true;
                    break;
                }
        }
        if (!atLeastOne) {
            JOptionPane.showMessageDialog(null, "Must have at least one mode enabled\nkeeping last selection");
            for (Map.Entry&lt;StationMode, JCheckBox&gt; entry : c_checkBoxes.entrySet()) {
                if (entry.getValue().getText().contentEquals(boxName)) {
                    entry.getValue().setSelected(true);
                    enabledModes.add(entry.getKey());
                    break;
                }
            }
        }
    }

    public void addAllowed(StationMode mode) {
        allowedModes.add(mode);
    }
     
    public boolean isAllowed(StationMode mode) {
       return allowedModes.contains(mode);
    }
   
    public void addEnabled(StationMode mode) {
        enabledModes.add(mode);
    }
    
    public boolean isEnabled(StationMode mode) {
       return enabledModes.contains(mode);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // &lt;editor-fold defaultstate="collapsed" desc="Generated Code"&gt;//GEN-BEGIN:initComponents
    private void initComponents() {

        setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        setFont(getFont().deriveFont(getFont().getStyle() &amp; ~java.awt.Font.BOLD));
        setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.Y_AXIS));
    }// &lt;/editor-fold&gt;//GEN-END:initComponents

    @Override
    public void actionPerformed(ActionEvent e) {
        
        e = new ActionEvent(this, e.getID(), e.getActionCommand());
        for (ActionListener l : c_listeners.getListeners(ActionListener.class)) {
            l.actionPerformed(e);
        }
    }

    public void addActionListener(ActionListener l) {
        c_listeners.add(ActionListener.class, l);
    }

    public void removeActionListener(ActionListener l) {
        c_listeners.remove(ActionListener.class, l);
    }

    @Override
    public void focusGained(FocusEvent e) {
        e = new FocusEvent(this, e.getID());
        processFocusEvent(e);
    }

    @Override
    public void focusLost(FocusEvent e) {
        e = new FocusEvent(this, e.getID());
        processFocusEvent(e);
    }

    public String serializeAllowedModes () {
        return serializeModes(allowedModes);
    }
    
    public String serializeEnabledModes () {
        return serializeModes(enabledModes);
    }

    private String serializeModes(ArrayList&lt;StationMode&gt; modes) {
        StringBuffer buffer = null;
        if (modes != null) {
            for (StationMode mode : modes) {
                // debugging for Larry
                if (mode == null) {
//                    System.err.println("Station mode serializeModes mode is null");
//                    JOptionPane.showMessageDialog(Weps.getInstance(), "Station mode serializeModes mode is null\nAdding data to logfile");
//                    LOGGER.error("Station mode serializeModes mode is null, dumping modes:");
//                    for (StationMode modeTemp : modes) {
//                            LOGGER.error("   Station mode serializeModes mode is null, mode val:"+modeTemp);
//                        if (modeTemp != null) {
//                            LOGGER.error("                                             mode name:"+modeTemp.getName());
//                        }
//                    }
//                    LOGGER.error("Station mode serializeModes mode is null, dumping allowed modes:");
//                    if (allowedModes != null) {
//                        for (StationMode modeTemp : allowedModes) {
//                                LOGGER.error("   Station mode serializeModes mode is null, allowed mode val:"+modeTemp);
//                            if (modeTemp != null) {
//                                LOGGER.error("                                             allowed mode name:"+modeTemp.getName());
//                            }
//                        }
//                    } else {
//                        LOGGER.error("Station mode serializeModes mode is null, allowed modes: null");
//                    }
//                    LOGGER.error("Station mode serializeModes mode is null, dumping enabled modes:");
//                    if (enabledModes != null) {
//                        for (StationMode modeTemp : enabledModes) {
//                                LOGGER.error("   Station mode serializeModes mode is null, enable mode val:"+modeTemp);
//                            if (modeTemp != null) {
//                                LOGGER.error("                                             enable mode name:"+modeTemp.getName());
//                            }
//                        }
//                    } else {
//                        LOGGER.error("Station mode serializeModes mode is null, enabled modes: null");
//                    }
                } else {
                    if (buffer == null) {
                        buffer = new StringBuffer(mode.getName());
                    } else {
                        buffer.append(",");
                        buffer.append(mode.getName());
                    }
                }
            }
        }
        return buffer != null ? buffer.toString() : "";
    }

    public void deserializeAllowedModes (String modeStr) {
        allowedModes.clear();
        deserializeModes (modeStr, allowedModes);
    }

    public void deserializeEnabledModes (String modeStr) {
        enabledModes.clear();
        deserializeModes (modeStr, enabledModes);
    }
    
    private void deserializeModes(String modeStr, ArrayList&lt;StationMode&gt; modes) {
        if (modeStr.length() &gt; 0) {
            String[] parts = modeStr.split(",");
            for (String part : parts) {
                part = part.trim();
                try {
                    StationMode mode = StationMode.parse(part);
                    if (mode != null) {
                        modes.add(mode);
                    } else {
                        LOGGER.warn("Unable to parse station mode str: " + modeStr);
                        LOGGER.warn("Unable to parse station mode: " + part);
                    }
                } catch (Exception e) {
                    LOGGER.warn("Unable to parse station mode: " + part);
                }
            }
            updateCheckBoxes();
        }
    }

    private void updateDefaults () {
        defaultsVals.clear();
        defaultList.removeAllItems();
        for (Map.Entry&lt;StationMode, JCheckBox&gt; entry : c_checkBoxes.entrySet()) {
            if (entry.getValue().isVisible() &amp;&amp; entry.getValue().isSelected()) {
                defaultsVals.add(entry.getKey().getDisplayName());
                defaultList.addItem(entry.getKey().getDisplayName());
            }
        }
        if (defaultListSel.length() &gt; 0) {
            defaultList.setSelectedItem(defaultListSel);
        }
    }
    
    public String getDefaultMode () {
        return defaultListSel;
    }
    
    public void setDefaultMode (String val) {
        if (val != null) {
            defaultListSel = val;
            defaultList.setSelectedItem(val);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
</pre></body></html>