package simpledb.test;

import simpledb.*;
import java.util.*;
import java.io.*;

public class Test {
    final static int MAX_COLUMNS = 128;
    final static int MAX_TABLES = 3;
    Database db;
    
    DbFile file[][]; 
    DbFile hashfile[][];

    /*
     * Create all tables of up to 128 columns.
     * The table with 1 column is in a file called "f0.dat"
     * The table with 2 columns is in a file called "f1.dat"
     * ...
     */
    public Test() {
	
	// System.out.println("STARTED");
	
	file = new HeapFile[MAX_COLUMNS][MAX_TABLES];
	
	for(int i=0; i<MAX_COLUMNS; i++) {
	    Type ta[] = new Type[i+1];
	    for(int j=0; j<i+1; j++)
		ta[j] = Type.INT_TYPE;
	    TupleDesc t = new TupleDesc(ta);
	    for(int k=0; k<MAX_TABLES; k++) {
		file[i][k] = new HeapFile(new File("f" + i + "." + k + ".dat"));
		Database.getCatalog().addTable(file[i][k], t);
	    }
	}
	
	hashfile = new ExHashFile[MAX_COLUMNS][MAX_TABLES];
	for(int i=0; i<MAX_COLUMNS; i++) {
		Type[] ta = new Type[i+1];
		for(int j=0; j<i+1; j++)
			ta[j] = Type.INT_TYPE;
		TupleDesc t = new TupleDesc(ta);
		for(int k=0; k<MAX_TABLES; k++){
		    hashfile[i][k] = new ExHashFile(new File("f" + i + "." + k + ".h"), 0);
		    Database.getCatalog().addTable(hashfile[i][k], t);
		}
	}
	
    }

    public void dump(TransactionId tid, DbIterator dbi) 
	throws TransactionAbortedException {
	try {
	    dbi.open();
	} catch (DbException e) {
	}
	
	try {
	    while (true) {
		Tuple tup = dbi.getNext();
		tup.print();
	    }
	} catch(DbException e) {
	    System.out.println("unexpected DbException");
	    dbi.close();
	} catch(NoSuchElementException e) {
	    dbi.close();
	}
    }

    public void dump(Query q) {
	try {
	    q.start();
	    while (true) {
		Tuple tup = q.getNext();
		tup.print();
	    }
	} catch (DbException e) {
	    e.printStackTrace();
	} catch (NoSuchElementException e) {
	    // q has been closed when q catch NoSuchElementException
	    // so here do nothing.
	} catch (IOException e) {
	    e.printStackTrace();
	} catch (TransactionAbortedException e) {
	    e.printStackTrace();
	}
    }

    public void dump(TransactionId tid, DbFile file) throws TransactionAbortedException {
	SeqScan ss = new SeqScan(tid, file.id());
	dump(tid, ss);
    }
    
    public void dump(DbFile file) throws TransactionAbortedException, IOException  {
	TransactionId tid = new TransactionId();				
	SeqScan ss = new SeqScan(tid, file.id());
	dump(tid, ss);
	Database.getBufferPool().transactionComplete(tid);
    }

    public boolean runTest(String args[]) {
	return false;
    }
}
