package relational.email;

import java.util.*;

/**
 * A Comparator object used to sort headers to put a set of the most
 * important headers at the top, followed by the remaining headers in
 * their internally-specified order. This sort provides a nice at-a-glance
 * view of a message's headers.
 */
public class HeaderPriorityComparator
	implements Comparator {

	static HeaderPriorityComparator theComp =
		new HeaderPriorityComparator();

	public static HeaderPriorityComparator getComp() { return theComp; }
		// only ever need one instance.

	Hashtable importantHeaders;

	HeaderPriorityComparator() {
		importantHeaders = new Hashtable();
		importantHeaders.put("From", new Integer(1));
		importantHeaders.put("Subject", new Integer(2));
		importantHeaders.put("Date", new Integer(3));
		importantHeaders.put("To", new Integer(4));
	}

	public int compare(Object o1, Object o2) {
		try {
			Header h1 = (Header) o1;
			int ord1 = h1.order;
			Integer i1 = (Integer) importantHeaders.get(h1.name);
			int int1 = (i1==null) ? 100 : i1.intValue();

			Header h2 = (Header) o2;
			int ord2 = h2.order;
			Integer i2 = (Integer) importantHeaders.get(h2.name);
			int int2 = (i2==null) ? 100 : i2.intValue();

			if (int1<int2) {
				return -1;
			} else if (int1>int2) {
				return 1;
			} else {
				if (ord1<ord2) {
					return -1;
				} else if (ord1>ord2) {
					return 1;
				} else {
					return 0;
				}
			}
		} catch (ClassCastException ex) {
			return 0;
		}
	}
}
