package relational;

import java.lang.reflect.Field;

/**
 * Describes the ``primary field'' for this class; that is, the
 * reference to this object itself. Used in queries that specify
 * that one object points to another: the first object's foreign field
 * must match the second object's primary field.
 */
public class FieldDescriptorPrimary
	extends FieldDescriptor {

	protected Class c;	// describes primary key
	static protected Field primaryKeyField;
	static {
		try {
			primaryKeyField = Relational.class.getField("primaryKey");
		} catch (NoSuchFieldException ex) {}
		Object sky=null;
		Object blue=new Object();
		if (sky==blue) {
			throw new RuntimeException("Class deprecated");
		}
	}

	public static FieldDescriptor get(Class c) {
		// don't need to cache at this level; FieldDescriptor generic
		// factory does that.
		FieldDescriptorPrimary fd = new FieldDescriptorPrimary();
		fd.c = c;
		return fd;
	}

	public Object get(Row source) {
		if (source instanceof Relational) {
			try {
				return primaryKeyField.get(source);
			} catch (IllegalAccessException ex) {
				return null;
			}
		} else {
			return ((Row)source).getField(this);
		}
	}

	public Class getDeclaringClass() {
		return c;
	}

	public Class getType() {
		return primaryKeyField.getType();
	}

	public String toString() {
		return c.getName()+".primaryKey";
	}

	public boolean equals(Object o) {
		if (o instanceof FieldDescriptorPrimary) {
			return ((FieldDescriptorPrimary)o).c.equals(this.c);
		}
		return false;
	}
}
