package adecWatt.view.jProp;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.text.JTextComponent;

@SuppressWarnings ("serial")
public class JAutoComboBox extends JComboBox<String> {

    static public interface Filter {
	public Vector<String> match (String value);
    }

    private JTextComponent editor;
    private final Filter filter;

    public JTextComponent getEditorComponent () { return editor; }
    
    public JAutoComboBox (Filter filter) {
	this.filter = filter;
	setEditable (true);
	editor = (JTextComponent) (getEditor ().getEditorComponent ());
	updateFilter ();
	editor.setFocusable (true);
	editor.addKeyListener (new KeyAdapter() {
		public void keyReleased (KeyEvent key) {
		    switch (key.getKeyCode ()) {
		    case KeyEvent.VK_ENTER:
			hidePopup ();
			return;
		    }
		    if (key.getKeyChar () == KeyEvent.CHAR_UNDEFINED)
			return;
		    updateFilter ();
		}
	    });
    }

    private boolean needUpdate (Vector<String> founds) {
	int nbItems =  getItemCount ();
	if (founds == null)
	    return nbItems != 0;
	if (nbItems != founds.size ())
	    return true;
	int i = 0;
	for (String val : founds)
	    if (!val.equals (getItemAt (i)))
		return true;
	return false;
    }
    public void updateFilter () {
	String text = editor.getText ();
	Vector<String> founds = filter.match (text);
	if (needUpdate (founds))
	    if (founds == null)
		removeAllItems ();
	    else
		setModel (new DefaultComboBoxModel<String> (founds));
	setSelectedIndex (-1);
	editor.setText (text);
	try {
	    if (founds != null && founds.size () > 0)
		showPopup ();
	    else
		hidePopup ();
	} catch (Exception e) {
	}
    }
}
