/*
 * Created on Dec 11, 2004
 *
 */
package gov.nasa.jsc.plum.DBManager;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.Vector;

/**
 * @author randrews
 *
 */
public class Database {
	private Vector tables,data;
	private static final char TERMINATOR = ';';
	
	/**
	 * @param conn The connection to the database
	 * @param savestructure Whether to include the code to make the tables
	 * @param savedata Whether to include the code to insert the rows
	 * @param clean Whether to "clean" the structure; not actually used
	 */
	public Database(Connection conn,boolean savestructure,boolean savedata){
		if(savestructure)tables=new Vector();
		if(savedata)data=new Vector();
		try {
			ResultSet res = conn.createStatement().executeQuery("show tables");
			while (res.next()) {
				String tblname = res.getString(1);
				if(savestructure)tables.add(new Table(tblname,conn));
				if(savedata)data.add(new DataSet(tblname,conn));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    
	/**
     * This constructor is just like the other one, if called with true, true.
	 * @param conn The connection to the database
	 */
	public Database(Connection conn){
		tables=new Vector();
		data=new Vector();
		try {
			ResultSet res = conn.createStatement().executeQuery("show tables");
			while (res.next()) {
				String tblname = res.getString(1);
				tables.add(new Table(tblname,conn));
				data.add(new DataSet(tblname,conn));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    
	/**
     * Prints SQL code to generate this Database to a file.
	 * @param filename The filename to print to
	 */
	public void toFile(String filename){
		try {
			FileOutputStream file=new FileOutputStream(filename);
			file.write(new String("#").getBytes());
			if(tables!=null)
				file.write(new String(" structure").getBytes());
			if(data!=null)
				file.write(new String(" data").getBytes());
			file.write(new String("\n").getBytes());
			if(tables!=null)
				for(int n=0;n!=tables.size();n++)
				{
					Table t=(Table)tables.get(n);
					file.write(t.toString().getBytes());
					file.write('\n');
				}
			
			if(data!=null)
				for(int n=0;n!=data.size();n++)
				{
					DataSet d=(DataSet) data.get(n);
					d.write(file);
				}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
