package simpledb.test;

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

public class HashDeleteTest extends Test {

    public boolean runTest(String args[]) {
	TransactionId tid = new TransactionId();
	SeqScan ss = new SeqScan(tid, 
				 hashfile[Integer.parseInt(args[1])-1][0].id());
	Predicate p = new Predicate(Integer.parseInt(args[2]),
				    Predicate.Op.getOp(args[3]),
				    new IntField(new Integer(args[4])));

	Filter f = new Filter(p, ss);
	Delete delOp = new Delete(tid, f);

	Type typeAr[] = new Type[1];
	typeAr[0] = Type.INT_TYPE;
	TupleDesc returnTD = new TupleDesc(typeAr);

	Query q = new Query(delOp, 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[5]))
			throw new DbException("delete returned wrong number.");
		}
	    } catch(NoSuchElementException e) {
		delOp.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 flushing
	try {
	    dump(tid, hashfile[Integer.parseInt(args[1])-1][0]);
	} catch (TransactionAbortedException te) {
	    te.printStackTrace();
	    return false;
	}

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

	return true;
    }
}
