package dbms;

import java.util.Vector;
import java.sql.*;

public class SQLResult {
	
	private SQLResultRow m_headers;
	private Vector<SQLResultRow> m_data;
	
	public SQLResult() {
		m_headers = new SQLResultRow();
		m_data = new Vector<SQLResultRow>();
	}
	
	public SQLResult(ResultSet rs) {
		// initialize the headers and data storage
		m_headers = new SQLResultRow();
		m_data = new Vector<SQLResultRow>();
		
		if(rs == null) { return; }
		
		// parse through the result set
		try {
			ResultSetMetaData meta = rs.getMetaData();
			
			if(meta == null) { return; }
			
			// store the headers
			for(int i=1;i<=meta.getColumnCount();i++) {
				m_headers.add(meta.getColumnName(i));
			}
			
			// store the tuple data
			while(rs.next()) {
				SQLResultRow rowData = new SQLResultRow();
				for(int i=1;i<=meta.getColumnCount();i++) {
					rowData.add(rs.getString(i));
				}
				m_data.add(rowData);
			}
		}
		catch(SQLException e) { }
	}
	
	// get the number of columns (headers)
	public int getColumnCount() {
		return m_headers.size();
	}
	
	// get the number of rows (tuples)
	public int getRowCount() {
		return m_data.size();
	}
	
	// get the headers
	public SQLResultRow getHeaders() {
		return m_headers;
	}
	
	// get a specific header
	public String getHeader(int index) {
		if(index < 0 || index >= m_headers.size()) { return null; }
		return m_headers.elementAt(index);
	}
	
	// get the table rows (tuples)
	public Vector<SQLResultRow> getData() {
		return m_data;
	}
	
	// get a specific row (tuple)
	public SQLResultRow getRow(int row) {
		if(row < 0 || row >= m_data.size()) { return null; }
		return m_data.elementAt(row);
	}
	
	// get a specific element from the specified row (tuple)
	public String getElement(int row, int index) {
		if(row < 0 || row >= m_data.size()) { return null; }
		if(index < 0 || index >= m_data.elementAt(row).size()) { return null; }
		return m_data.elementAt(row).elementAt(index);
	}
	
	// return out a string representation of the table
	public String toString() {
		String s = m_headers.toString();
		for(int i=0;i<m_data.size();i++) {
			s += "\n" + m_data.elementAt(i).toString();
		}
		return s;
	}
	
}
