package adecWatt.view.jProp;

import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.text.JTextComponent;

import adecWatt.model.unit.Building;
import adecWatt.view.JEditable;
import static adecWatt.model.Prop.PropMix;

public class JPropBuilding extends JPLabel implements JAutoComboBox.Filter {

    // ========================================
    protected ArrayList<Building> allBuidings;
    protected ArrayList<String> allBuidingsName;
    protected Vector<Building> matchBuidings;

    protected JAutoComboBox choice;

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

    @Override
    public Vector<String> match (String value) {
	value = value.toLowerCase ();
	Vector<String> founds = new Vector<String> ();
	matchBuidings.clear ();
	if (allBuidings != null) {
	    for (Building building : allBuidings) {
		if (building.parentMatch (value)) {
		    founds.add (building.getLocalName ());
		    matchBuidings.add (building);
		}
	    }
	}
	return founds;
    }
    
    protected boolean verify (JTextComponent editor) {
	if (editor == null || allBuidingsName == null)
	    return false;
	boolean result = allBuidingsName.contains (editor.getText ());
	editor.setBorder (result ? defaultBorder : badValueBorder);
	return result;
    }

    protected JComponent getValue () {
	if (lastValue == null)
	    return null;
	if (lastValue == PropMix)
	    return getUnknownLabel ();
	try {
	    return new JLabel (permanentDB.getUnitById (lastValue).getName ());
	} catch (Exception e) {
	    return getMsgLabel (lastValue);
	}
    }

    protected JComponent getEditor () {
	allBuidings = permanentDB.getAllBuildings ();
	int index = -1;
	if (allBuidings != null) {
	    allBuidingsName = new ArrayList<String> (allBuidings.size ());
	    for (Building building : allBuidings) {
		if (lastValue != null && building.getId ().equals (lastValue))
		    index = allBuidingsName.size ();
		allBuidingsName.add (building.getLocalName ());
	    }
	} else
	    allBuidingsName = new ArrayList<String> (0);
	matchBuidings = new Vector<Building> (allBuidingsName.size ());
	choice = new JAutoComboBox (this);
	JTextComponent editor = choice.getEditorComponent ();
	defaultBorder = editor.getBorder ();
	editors = new JTextComponent [] {editor};
	setChangeListener (editor);
	if (index >= 0)
	    choice.setSelectedIndex (index);
	return choice;
    }

    public String getLastValue () {
	String val = "";
	int index = choice.getSelectedIndex ();
	if (index >= 0)
	    val = matchBuidings.get (index).getId ();
	if (unchanged.size () > 0)
	    val = PropMix;
	return val;
    }

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