package adecWatt.view.jProp;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.text.JTextComponent;

import misc.Util;

import adecWatt.model.InseeDB;
import adecWatt.view.JEditable;

public class JPropCity extends JPLabel implements JAutoComboBox.Filter {
    static public final int maxPropal = 500;

    protected JComponent[] jComponents = new JComponent[2];
    protected JAutoComboBox jCity;

    protected ArrayList<InseeDB.Insee> filteredCity;

    // ========================================
    protected void plotCity () {
	if (filteredCity == null)
	    return;
	int nbInsee = filteredCity.size ();
	int idx = jCity.getSelectedIndex ();
	if (nbInsee == 1)
	    idx = 0;
	if (idx < 0)
	    return;
	InseeDB.Insee insee = filteredCity.get (idx);
	jEditable.plotCity (insee.latitude, insee.longitude);
    }

    public Vector<String> match (String value) {
	try {
	    filteredCity = adecWatt.getInseeDB ().getCities (value);
	} catch (Exception e) {
	    filteredCity = null;
	}
	if (filteredCity == null)
	    return null;
	if (filteredCity.size () > maxPropal) {
	    filteredCity = null;
	    return null;
	}
	Vector<String> filteredCityName = new Vector<String> (filteredCity.size ());
	for (InseeDB.Insee insee : filteredCity)
	    filteredCityName.add (insee.name);
	return filteredCityName;
    }

    public JPropCity (String propName, JEditable jEditable) {
	super (propName, jEditable);
    }

    protected JComponent getEditor () {
	jCity = new JAutoComboBox (this);
	JTextComponent editor = jCity.getEditorComponent ();
	editors = new JTextComponent [] {editor};
	setChangeListener (editor);
	editor.setText (lastValue);
	jCity.updateFilter ();
	JPanel jPanel = new JPanel ();
	jPanel.add (jCity);
	jPanel.add (Util.newIconButton ("PlotCity", new ActionListener () {
		public void actionPerformed (ActionEvent e) {
		    plotCity ();
		}
	    }));
	Util.unBoxButton (jPanel);
	return jPanel;
    }

    // ========================================
}
