package pesquisa;

import java.awt.Dimension;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JScrollPane;
import java.lang.reflect.Field;
import java.lang.reflect.AccessibleObject;
import javax.swing.JComponent;
import javax.swing.JTable;

public class ObjectsPresentation {
  
  private Hashtable<Integer, Object> objects;

  Object selectedObject = null;
  
  private JTable presentationTable;
  
  Hashtable presentationFields;
  
  String[] headerFieldNames;
  
  JScrollPane scrollPane;
  
  /** Creates a new instance of ObjectsView */
  public ObjectsPresentation(Hashtable presentationFields) {
    objects = new Hashtable();
    presentationTable = new javax.swing.JTable();
    
    presentationTable.setBounds(10, 80, 410, 140);
    
    this.presentationFields = presentationFields;
    
    System.out.println("#presentationFields: " + presentationFields.size());
    
    headerFieldNames = new String[presentationFields.size()];
    int i = 0;
    for (Enumeration e = presentationFields.elements(); e.hasMoreElements() ;) {
      headerFieldNames[i++] = (String) e.nextElement();
    }

    PresentationTableModel tableModel = new PresentationTableModel(null,
            headerFieldNames,
            0,
            headerFieldNames.length);
    presentationTable.setModel(tableModel);
    
    presentationTable.setPreferredScrollableViewportSize(new Dimension(500, 70));

    //Create the scroll pane and add the presentationTable to it.
    scrollPane = new JScrollPane(presentationTable);
    
    scrollPane.setBounds(10, 80, 410, 140);
    
    presentationTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        tblResultsMouseClicked(evt);
      }
    });
  }
  
  JComponent getContainer() {
    return scrollPane;
  }
  
  public void presentObjects(Vector objectsToPresent) {
    String tableContents[][];

    try {
      System.out.println("#objectsToPresent = " + objectsToPresent.size());

      // Intancia uma matriz de strings para apresentar os objetos.
      tableContents = new String[objectsToPresent.size()][headerFieldNames.length];

      objects.clear();

      /**
       * Para cada objeto, preenche uma linha da matriz com o valores 
       * dos seus atributos de apresentação.
       */
      for(int row = 0; row < objectsToPresent.size(); row++) {
        Object obj = objectsToPresent.get(row);

        objects.put(new Integer(row), obj);
        
        /**
         * Para cada atributo de apresentação, obtém o seu valor e 
         * o adiciona na célula correspondente da matriz.
         */
        try {
          int col = 0;
          for(java.util.Enumeration en = presentationFields.keys(); en.hasMoreElements(); /* Nothing */) {
            String value = getAttributeValue(obj, (String) en.nextElement());
            tableContents[row][col] = value;
            System.out.println("[row][col] = " + tableContents[row][col]);
            col++;
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    
      presentationTable.setModel(new PresentationTableModel(tableContents, 
              headerFieldNames, 
              objectsToPresent.size(), 
              headerFieldNames.length));

    } catch(Exception exception) {
      exception.printStackTrace();
    }
  }
  
  Object getSelectedObject() {
    Integer indice = new Integer(presentationTable.getSelectedRow());
    System.out.println("Row of selected object: " + indice);
    return objects.get(indice);
  }

  public JTable getTable() {
    return presentationTable;
  }
  
  private void tblResultsMouseClicked(java.awt.event.MouseEvent evt) {
    Integer indice = new Integer(presentationTable.getSelectedRow());
    selectedObject = objects.get(indice);
    System.out.println("Index of selected object: " + indice);
  }

  protected String getAttributeValue(Object obj, String attribute) throws Exception {

    if(obj == null)
      throw new AssertionError();
    
    if(attribute == null)
      throw new AssertionError();

    System.out.println("Getting value of attribute: " + attribute);
    
    Field [] fields = obj.getClass().getDeclaredFields();
    AccessibleObject.setAccessible(fields, true);
    Field f = fields[0];
    
    for(int i = 0; i < fields.length; i++) {
      f = fields[i];
      if(f.getName().equals(attribute))
        return f.get(obj).toString();
    }

    return "nulo";
  }

  public String getSelectedObjectId()	{
    try {
      Object obj = getSelectedObject();
      if(obj != null)
        return getAttributeValue(obj, "id");
      else
        return "nulo";
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
