package relational.email;

import java.io.*;
import java.util.*;

/**
 * Sort headers by subject. This sort honors email conventions such as
 * Re:, so that threads sort together with the initial message that has
 * no Re: prefix.
 */
public class SubjectComparator
	implements Comparator, Serializable {

	public int compare(Object o1, Object o2) {
		String s1 = (String) o1;
		String s2 = (String) o2;

		// discard a leading Re:, and
		// discard any leading whitespace or punctuation
		s1 = trimPunct(trimRe(s1));
		s2 = trimPunct(trimRe(s2));

		return s1.compareToIgnoreCase(s2);
	}

	protected String trimRe(String s) {
		if (s.length()<2) {
			return s;
		}
		char c0 = s.charAt(0);
		char c1 = s.charAt(1);
		if (Character.toUpperCase(c0) == 'R'
			&& Character.toUpperCase(c1) == 'E') {
			return s.substring(2);
		} else {
			return s;
		}
	}

	protected String trimPunct(String s) {
		for (int i=0; i<s.length(); i++) {
			char ch = s.charAt(i);
			if (Character.isLetterOrDigit(ch)) {
				return s.substring(i);
			}
		}
		return "";
	}
}
