package simpledb;

import java.io.*;

/**
 * Instance of Field that stores a single integer.
 */
public class IntField implements Field {
    int myVal;

    /**
     * Constructor.
     *
     * @param i The value of this field.
     */
    public IntField(Integer i) {
	this.myVal = i.intValue();
    }

    public String toString() {
	return new Integer(myVal).toString();
    }
    
    public int hashCode() {
	return myVal;
    }
    
    public boolean equals(Object field) {
	return ((IntField) field).myVal == myVal;
    }
    
    public void serialize(DataOutputStream dos) throws IOException {
	dos.writeInt(myVal);
    }

    public int value() {
        return myVal;
    }

    /**
     * Compare the specified field to the value of this Field.
     * Return semantics are as specified by Field.compare
     *
     * @throws IllegalCastException if val is not an IntField 
     * @see Field#compare
     */
    public boolean compare(Predicate.Op op, Field val) {

	IntField iVal = (IntField) val;

	switch (op) {
	case EQUALS: 
	    return myVal == iVal.myVal;

	case GREATER_THAN: 
	    return myVal > iVal.myVal;
	    
	case GREATER_THAN_OR_EQ: 
	    return myVal >= iVal.myVal;
	    
	case LESS_THAN: 
	    return myVal < iVal.myVal;

	case LESS_THAN_OR_EQ: 
	    return myVal <= iVal.myVal;
	}

	return false;
    }

    public String toStr() {
        return Integer.toString(myVal);
    }
}
