package voi.votable;

import java.io.*;
import java.sql.*;
import voi.vowrite.*;
import voi.routines.*;

public class VoTableWriter 
{
	private OutputStream outStream;
	private VOTableStreamWriter voWrite;
	private VOTable vot;
	private VOTableTable voTab;
	private ResultSet results;
	private boolean[] queryFlags;
	private	String[] rowData;	
	private String [] columnNames = new String[0];		

	
	public VoTableWriter (OutputStream outStream,
			      ResultSet results,
			      VOTableTable voTab,
			      boolean queryFlags[])
	{
		this.outStream = outStream;
		this.results = results;
		this.voTab = voTab;
		this.queryFlags = queryFlags;
	}
	
	public void writeToVoTable ()
	{
		PrintStream prnStream = new PrintStream (outStream);
		voWrite = new VOTableStreamWriter (prnStream);
		VOTable vot = new VOTable ();
		voWrite.writeVOTable (vot);
		VOTableResource voResource = new VOTableResource ();
		voWrite.writeResource (voResource);
		voWrite.writeTable (voTab);
		
		try
		{
		// add the metaData 
			ResultSetMetaData metadata = results.getMetaData ();
			
			int columns = metadata.getColumnCount ();
			if (queryFlags [9]) columns++;
			columnNames = new String [columns];
			
			
			int i; // loop variable
			for (i = 0; i < metadata.getColumnCount (); i++)
			columnNames [i] = metadata.getColumnLabel(i+1);
		
			/** add absolute magnitude if it is selected by the user **/		
			if (queryFlags[9]) columnNames [i] = "Absolute Magnitude";

		
			boolean test = results.first ();
			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 (queryFlags[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]);
					double absMag = 0.00;
					if (z1 != 0)
					{	
						Magnitude.setParameters (100.0,0.5,0.5); // set the parameters for the Magnitude class
						double temp1 = Magnitude.getAbsoluteMagnitude (bj, z1); // obtain absolute magnitude
						int temp2 = (int) (temp1 * 100);
						absMag = (double) temp2 / 100;
					}
					rowData [i] = Double.toString (absMag);
				}
				voWrite.addRow (rowData, columns);	
				
			}
		}
		catch (SQLException sqle)
		{
			System.err.println (sqle);
		}
			
		voWrite.endTable ();
		voWrite.endResource ();
		voWrite.endVOTable ();
	}
	
	public int getIndex (String name, int columns)
	{
		for (int i = 0; i < columns; i++)
			if (columnNames[i].equals (name)) 
				return i;
		return 0;
	}

}
	
		
			      
	
	
