package voi.votable;

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

/**
This class writes the SQL ouput data in VOTable format 
*/
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];		

	/**
	This constructor accepts the following
	1) outStream
	2) SQL ResultSet
	3) MetaData for the VOTable in form a VOTableTable object
	4) queryFlags which tell the program what to choose from
	*/	
	public VoTableWriter (OutputStream outStream,
			      ResultSet results,
			      VOTableTable voTab,
			      boolean queryFlags[])
	{
		this.outStream = outStream;
		this.results = results;
		this.voTab = voTab;
		this.queryFlags = queryFlags;
	}
	
	/**
	The function calls subfucntions
	1) SetProperties
	2) getSqlData
	3) closeVOTable
	*/
	public void writeToVoTable ()
	{
		setProperties ();		
		getSqlData ();		
		closeVOTable ();
	}
	
	/**
	This fucntion sets the properties for of the VoTableWriter class
	by setting the initialisation of certain objects such as :
	1) voWrite (VOTableStreamWriter class) 
	2) vot (VOTABLE class)
	*/
	public void setProperties ()
	{
		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);
	}
	
	/**
	This function gets the SQL data and writes it to the VOTable class
	*/
	public void getSqlData ()
	{
		AssembleQueryResults assembleQuery = new AssembleQueryResults (results, queryFlags);
		columnNames = assembleQuery.getColumnNames ();	
		int columns = assembleQuery.getTotalColumns ();
		
		try
		{
			// test is used bcoz for using ResultSet.first () we need a boolean return type
			boolean setToFirst = results.first ();
			while (results.next ())
			{
				rowData = assembleQuery.getRowData (results);	
				voWrite.addRow (rowData, columns);
			}
		}
		catch (SQLException e)
		{
			System.out.println (" SQL exception while adding rows to VOTable ");
		}
	}
	
	/**
	This functions releases the resources held by the vot object
	*/
	public void closeVOTable ()
	{
		voWrite.endTable ();
		voWrite.endResource ();
		voWrite.endVOTable ();		
	}
}
	
		
			      
	
	
