package relational;

import java.io.*;
import java.lang.reflect.Field;

public class FieldDescriptorReference
	extends FieldDescriptor {

	protected Class c;	// describes primary key

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

	public Object get(Row source) {
		if (source instanceof Relational) {
			try {
				if (c.isInstance(source)) {
					return source;
				}
				throw new
					IllegalAccessException("source object has wrong class");
			} catch (IllegalAccessException ex) {
				return null;
			}
		} else {
			return ((Row)source).getField(this);
		}
	}

	public Class getDeclaringClass() {
		return c;
	}

	public Class getType() {
		return Object.class;
	}

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

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

	private void writeObject(java.io.ObjectOutputStream out)
		throws IOException {
		out.writeObject(c.getName());
	}

	private void readObject(java.io.ObjectInputStream in)
		throws IOException, ClassNotFoundException {
		String className = (String) in.readObject();
		c = Class.forName(className);
	}

	Object readResolve()
		throws ObjectStreamException {
		// Get the "official" instance of FieldDescriptor (from the cache),
		// so that hashCode/equals works right
		return FieldDescriptor.get(c);
	}
}
