package sdsi;
import sdsi.sexp.*;

/**
 * The (* prefix <byte-string>) special form tag. Represents all
 * byte-strings with <byte-string> as a prefix.
 */
class TEPrefix
	extends TESpecial {

	SexpString prefix;

	String mySpecialToken() { return "prefix"; }
	
	public TEPrefix(SexpString prefix) {
		this.prefix = prefix;
		Sexp sexpary[] = new Sexp[3];
		sexpary[0] = new SexpString("*");
		sexpary[1] = new SexpString(mySpecialToken());
		sexpary[2] = prefix;
		srep = new SexpList(sexpary);
	}

	public TEPrefix(SexpList l)
		throws SexpParseException{
		super(l);
		requireArgs(1);
		this.prefix = (SexpString) l.elementAt(2);
	}

	public TagExpression intersect(TagExpression otherTE) {
		if (otherTE instanceof TEByteString) {
			SexpString otherString = ((TEByteString) otherTE).value;
			if (otherString.startsWith(prefix)) {
				return otherTE;
			} else {
				return TENull.getNull();
			}
		} else if (otherTE instanceof TEPrefix) {
			SexpString otherPrefix = ((TEPrefix) otherTE).prefix;
			int myLength = prefix.stringContent().length();
			int otherLength = otherPrefix.stringContent().length();
			if (myLength >= otherLength) {
				return this;
			} else {
				return otherTE;
			}
		} else if (otherTE instanceof TESet) {
			// the set knows what to do
			return otherTE.intersect(this);
		} else if (otherTE instanceof TERange) {
			System.err.println("Don't know how to intersect range & prefix");
			return TENull.getNull();
		} else {
			// doesn't intersect with listy things
			return TENull.getNull();
		}
	}	 
}
