package org.openspml.browser;

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

// avoid awt conflict
import java.util.List;

import org.openspml.util.*;
import org.openspml.message.*;

public class SearchTableModel extends DefaultTableModel {

    public SearchTableModel(SearchResponse res) {
	build(res);
    }

    private void build(SearchResponse response) {

	// first column is always object identity
	addColumn("Identifier");

	// other columns defined by result attributes
	List cols = getResultColumns(response);
	if (cols != null) {
	    // sorting?
	    for (int i = 0 ; i < cols.size() ; i++) 
		addColumn((String)cols.get(i));
	}

	List results = response.getResults();
	if (results != null) {
	    Iterator it = results.iterator();
	    while (it.hasNext()) {
		SearchResult sr = (SearchResult)it.next();
		Vector row = new Vector();
		row.add(sr.getIdentifierString());

		if (cols != null) {
		    for (int i = 0 ; i < cols.size() ; i++) {
			String name = (String)cols.get(i);
			row.add(sr.getAttributeValue(name));
		    }
		}

		addRow(row);
	    }
	}
    }

    /**
     * Given an SearchResponse calculate a list of "columns"
     * that includes all possible attributes in the result.
     * We have to iterate over all the results in order to do this,
     * since there is no assurance that every SearchResult will have
     * the same attributes.
     *
     * Might want to move this into SpmlResponse.
     */
    private List getResultColumns(SearchResponse res) {

	// first one will be reserved for the object identity
	List columns = new ArrayList();
	
	// under what conditions would we have more than
	// one SearchResponse int he result?
	List results = res.getResults();
	if (results != null) {
	    Iterator it = results.iterator();
	    while (it.hasNext()) {
		SearchResult sr = (SearchResult)it.next();
		List atts = sr.getAttributes();
		if (atts != null) {
		    Iterator it2 = atts.iterator();
		    while (it2.hasNext()) {
			Attribute att = (Attribute)it2.next();
			String name = att.getName();
			if (name != null && !columns.contains(name))
			    columns.add(name);
		    }
		}
	    }
	}

	return columns;
    }

    public static void println(String msg) {
	System.out.println(msg);
    }
}
