package relational;

import java.util.Hashtable;
import java.util.Vector;
import java.lang.reflect.Field;
import Tools.Text;

/**
 * Test where a substring appears in a field.
 *
 * @classConcise true
 */
public class WhereLike
	extends WhereLiteral {
	FieldDescriptor fd;
	String s;
	boolean caseSensitive;
	boolean startsWith;
	boolean endsWith;

	public WhereLike(FieldDescriptor fd, String s, boolean caseSensitive,
		boolean startsWith, boolean endsWith) {
		this.fd = fd;
		this.s = s;
		this.caseSensitive = caseSensitive;
		this.startsWith = startsWith;
		this.endsWith = endsWith;
	}

	public WhereLike(FieldDescriptor fd, String s) {
		this(fd, s, false, false, false);
	}

	public boolean includes(Row ro, Database db) {
		Tools.Assert.assert(fd!=null && s!=null);
		String s1 = fd.get(ro).toString();
		String s2 = s;
		if (!caseSensitive) {
			s1 = s1.toUpperCase();
			s2 = s2.toUpperCase();
		}
		if (startsWith) {
			if (endsWith) {
				return s1.equals(s2);
			} else {
				return s1.startsWith(s2);
			}
		} else {
			if (endsWith) {
				return s1.endsWith(s2);
			} else {
				return s1.indexOf(s2)>=0;
			}
		}
	}

	public String toString() {
		String fieldName = (fd!=null) ? fd.toString() : "(null)";
		return "("+fieldName
			+(caseSensitive ? " Like " : " LIKE '")
			+(startsWith ? "" : "%")
			+s
			+(endsWith ? "" : "%")
			+"')";
	}

	// Children aren't the right model. This thing should have a custom
	// tree node editor.
	public int getChildCount() {
		return 2;
	}

	public Object getChild(int index) {
		if (index==0) {
			return fd;
		} else if (index==1) {
			return s;
		} else {
			throw new IllegalArgumentException("WhereLike has only 2 children");
		}
	}

	public void setChild(int index, Object child) {
		if (index==0) {
			fd = (FieldDescriptor) child;
		} else if (index==1) {
			s = (String) child;
		} else {
			throw new IllegalArgumentException("WhereLike has only 2 children");
		}
	}

	public FieldDescriptor getFieldDescriptor() {
		return fd;
	}

	public String getShortName() { return "like"; }
}
