package usda.weru.mcrew;

import com.klg.jclass.cell.JCCellInfo;
import com.klg.jclass.cell.editors.JCComboBoxCellEditor;
import java.awt.AWTEvent;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.function.BiConsumer;

/**
 *
 * @author mark
 */
public class KillComboBoxCellEditor extends JCComboBoxCellEditor {

    private static final long serialVersionUID = 1L;
    ArrayList<String> names;
    Hashtable<String,String> choices;
    JCComboBoxCellEditor empty = new JCComboBoxCellEditor();
    boolean haskilflag;
    
    public KillComboBoxCellEditor(Hashtable<String,String> choices) {
        super();
        
        this.choices = choices;
        names = new ArrayList<>();
        
        KillComboBoxSupport.parseChoices(this, choices, names);
    }
    
    @Override
    public void initialize(AWTEvent ev, JCCellInfo cellInfo, Object o) {
        haskilflag = KillComboBoxSupport.setComboItems(this, cellInfo, choices, names);
    }
    
    @Override
    public Object getCellEditorValue() {
        String selected = (String)this.getSelectedItem();
        // The value saved in the cfg file is the key value, not the
        // text in the ComboBox.
        // This looks up the key to be returned using the selected
        // Combo text value.
        if (haskilflag && choices != null) {
            MyGetKeyFromValCompare comparator = new MyGetKeyFromValCompare (selected);
            choices.forEach(comparator);
            return comparator.getKey();
        } else {
            return "";
        }
    }
 
    @Override
    public Component getComponent() {
        return(this);
    }
        
    public class MyGetKeyFromValCompare implements BiConsumer <String, String> {
        String val;
        String key;
        
        public MyGetKeyFromValCompare (String srchVval) {
            val = srchVval;
            key = "";
        }
        
        @Override
        public void accept(String t, String u) {
            try{
                if (val.equals(u)) {
                    key = t;
                }
            }catch(NullPointerException e){
                
            }
          
        }
        
        String getKey () {
            return key;
        }
    }
}
