package org.jcon.inspect;

import org.jcon.util.ArraySorter;
import org.jcon.util.Hub;
import java.beans.PropertyDescriptor;
import java.util.Hashtable;
import java.util.Vector;
import java.lang.reflect.Method;

import javax.swing.JComponent;
import javax.swing.JTable;

/**
 * Your garden variety property sheet. This one only
 * displays properties, allowing no edits. Drill down now.
 * Edits later. CONTROLLER.
 *
 * @author Jack Harich
 */
public class PropertySheet implements ArraySorter.Comparer {

//---------- Private Fields ------------------------------
private PropertySheetView view = new PropertySheetView();
private PropertyDescriptor[] pds;
private Object instance;

//---------- Initialization ------------------------------
// (none)

//---------- ArraySorter.Comparer Implementation ---------
public int compare(Object a, Object b) {
    // Sort PropertyDescriptor[] by getName(). This should be in BeanInfo or...
    PropertyDescriptor da = (PropertyDescriptor)a;
    PropertyDescriptor db = (PropertyDescriptor)b;

    String aName = da.getName();
    String bName = db.getName();

    return aName.compareTo(bName);
}
//---------- Public Methods ------------------------------
public void setHub(Hub hub) {
    view.setHub(hub);
}
public JComponent getComponent() {
    return view.getComponent();
}
public void loadProperties(PropertyDescriptor[] pds,
        Object instance) {
    this.pds = pds;
    this.instance = instance;
    refresh();
}
public void refresh() {
    view.emptyProperties();
    // Load table and rows
    ArraySorter.sort(pds, this);
    for (int i = 0; i < pds.length; i++) {
        PropertyDescriptor pd = pds[i];
        String name = pd.getName();
        // no longer needed if (name.equals("class")) continue; // In all

        Method reader = pd.getReadMethod();
        if (reader == null) continue;

        try {
            // Create BeanProperty
            Object[] args = { };
            Object value = reader.invoke(instance, args);
            BeanProperty property = new BeanProperty(value, pd);
            // Add to table and rows
            view.addProperty(property);

        } catch(Exception ex) {
            print(".loadProperties() - Property name = '" + name + "'\n");
            ex.printStackTrace();
            return;
        }
    }
}
//---------- Private Methods -----------------------------
//--- Std
private static void print(String text) {
    System.out.println("PropertySheet" + text);
}

} // End class
