package simpledb.test;

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

public class HashInsertTest extends Test {
   
    public boolean runTest(String args[]) {
	TransactionId tid = new TransactionId();
	SeqScan ss = new SeqScan(tid, file[Integer.parseInt(args[1])-1][0].id());

	Insert insOp = null;
	try {
	    insOp = new Insert(tid, ss, hashfile[Integer.parseInt(args[2])-1][1].id());
	} catch (DbException dbe) {
	    dbe.printStackTrace();
	    System.exit(-1);
	}

	Type typeAr[] = new Type[1];
	typeAr[0] = Type.INT_TYPE;
	TupleDesc returnTD = new TupleDesc(typeAr);
	
	Query q = new Query(insOp, tid);
    
	try {
	    q.start();
	    try {
		while(true) {
		    Tuple tup = q.getNext();
		    if(!tup.getTupleDesc().equals(returnTD))
			throw new DbException("wrong return type");
		    if(!tup.getField(0).toString().equals(args[3]))
			throw new DbException("insert returned wrong number");
		}
	    } catch(NoSuchElementException e) {
		insOp.close();
	    }
	} catch (TransactionAbortedException te) {
	    te.printStackTrace();
	    return false;	    
	} catch (DbException e) {
	    e.printStackTrace();
	    return false;
	} catch (IOException e) {
	    e.printStackTrace();
	    return false;
	}
	// dump contents before we flush
	try {
	    dump(tid, hashfile[Integer.parseInt(args[2])-1][1]);
	} catch (TransactionAbortedException te) {
	    te.printStackTrace();
	    return false;
	}

	// XXX hack for testing purposes
	try {
	    Database.getBufferPool().flushAllPages();
	} catch (Exception e) {
	    e.printStackTrace();
	}

	return true;
    }
}
