import java.sql.*;
import javax.swing.table.*;
import java.util.*;
import java.lang.String;
import java.lang.Object;

class ResultsModel extends AbstractTableModel
{
	String [] columnNames = new String[0];
	Vector dataRows;
	
	public void setResultSet (ResultSet results, boolean flags[], int DerivedCount)
	{
		
		for (int i = 0; i < 9; i++)
			System.out.println (flags[i]);
		
		System.out.println ("\n");
		
		try
		{
			ResultSetMetaData metadata = results.getMetaData ();
			
			int columns = metadata.getColumnCount () + DerivedCount;
			columnNames = new String [columns];
			
			// get the column names
			int i;
			for (i = 0; i < metadata.getColumnCount (); i++)
				columnNames [i] = metadata.getColumnLabel(i+1);
			
			if (flags[9]) columnNames [i] = "Absolute Magnitude";
			
			
			// get all rows
			dataRows = new Vector();
			String[] rowData;
			
			while (results.next ())
			{
				rowData = new String [columns];
				for (i = 0; i < metadata.getColumnCount (); i++)
					rowData [i] = results.getString (i+1);
				
				// if the absolute magnitude flag is set then it is required to 
				// convert the BJSEL and z to double and and the Calculate absMag
				// using the Magnitude Class, and add the data to rowData and columnNames

				if (flags[9])				// just for testing AbsMag is set to 3
				{
					int bjIndex = getIndex ("bj", columns);
					int z1Index = getIndex ("z1", columns);

					double bj = Double.parseDouble (rowData [bjIndex]);
					double z1 = Double.parseDouble (rowData [z1Index]);

					
					Magnitude.setParameters (100.0,0.5,0.5); // set the parameters for the Magnitude class
					double absMag = Magnitude.getAbsoluteMagnitude (bj, z1); // obtain absolute magnitude
					rowData [i] = Double.toString (absMag);
				}
				
				dataRows.addElement (rowData);

			}
			fireTableChanged (null);
		}
		catch (SQLException sqle)
		{
			System.err.println (sqle);
		}
	}
	
	public int getColumnCount ()
	{ 
		return columnNames.length;
	}
	
	public int getRowCount ()
	{
		if (dataRows == null)
			return 0;
		else 
			return dataRows.size ();
	}
	
	public Object getValueAt (int row, int column)
	{
		return ((String [])(dataRows.elementAt (row)))[column];
	} 
	
	public String getColumnName (int column)
	{
		if (columnNames [column] == null)
			return "No Name";
		else	
			return columnNames [column];
	}
	
// This function returns the index of the required columnname (ex. BJSEL, z etc..)	
	
	public int getIndex (String name, int columns)
	{
		for (int i = 0; i < columns; i++)
			if (columnNames[i].equals (name)) 
				return i;
		return 0;
	}
}
			
