package simpledb;

import java.util.*;

/**
 * SeqScan is an implementation of a sequential scan access method that reads
 * each tuple of a table in no particular order (e.g., as they are laid out on
 * disk).
 */
public class SeqScan implements DbIterator {
    private TransactionId tid;
    private int tableid;
    private DbFile dbFile;
    private TupleDesc tupleDesc;
    private DbFileIterator iter;

    /** 
     * Constructor.
     * Creates a sequential scan over the specified table as a part of the
     * specified transaction.
     *
     * @param tid The transaction this scan is running as a part of.
     * @param tableid the table to scan.
     */
    public SeqScan(TransactionId tid, int tableid) {
        this.tid = tid;
        this.tableid = tableid;
    }

    /**
     * Opens this sequential scan.
     * Needs to be called before getNext().
     */
    public void open() 
	throws DbException, TransactionAbortedException {
        dbFile = Database.getCatalog().getDbFile(tableid);
        tupleDesc = Database.getCatalog().getTupleDesc(tableid);
        iter = dbFile.iterator(tid);
        iter.open();
    }
    
    /**
     * Implementation of DbIterator.getTupleDesc method.
     */
    public TupleDesc getTupleDesc() {
        return tupleDesc;
    }
    
    /**
     * Implementation of DbIterator.getNext method.
     * Return the next tuple in the scan.
     *
     * @throws NoSuchElementException if the scan is complete. 
     */
    public Tuple getNext() 
	throws NoSuchElementException, TransactionAbortedException, DbException {
        return iter.getNext();
    }
    
    /**
     * Closes the sequential scan.
     */
    public void close() {
        dbFile = null;
        tupleDesc = null;
        iter = null;
    }
    
    /**
     * Rewinds the sequential back to the first record.
     */
    public void rewind() 
	throws DbException, NoSuchElementException, TransactionAbortedException {
        iter = dbFile.iterator(tid);
        iter.open();
    }
}
