package eworks.RQL.model;

import java.util.Hashtable;
import java.util.regex.*;
import eworks.RDF.model.*;

/**
 * <p>Represents a compare operator that compares a value against a regular
 * expression.</p>
 * 
 * @author Fabian Wleklinski (<a href="mailto:fabian@wleklinski.de">fabian@wleklinski.de</a>)
 * @version 1.00 (2003-11-03)
 * @see <a href="http://139.91.183.30:9090/RDF/RQL/" target="_blank">
 *      The RDF Query Language (RQL)</a>
 */
public class AlikenessCompareOperator extends CompareOperator {
		
	private Hashtable patternCache;
	
	/**
	 * Creates a new instance.
	 */
	public AlikenessCompareOperator() {
		this.patternCache = new Hashtable();
	}
		
	/**
	 * Matches a given value against a regular expression.
	 * @param op1 The value to compare against the regular expression <code>op2</code>.
	 * @param op2 The regular expression.
	 */
	public boolean compare(LiteralValue op1, LiteralValue op2) {
		Pattern p = (Pattern) this.patternCache.get(op2);
			
		if (p == null) {
			String reg = op2.toString();
			StringBuffer sb = new StringBuffer(reg.length() * 2);

			char[] chars = reg.toCharArray();
			boolean escaping = false; 
			for (int i=0; i<chars.length; i++) {
				if (! escaping && chars[i] == '\\')
					escaping = true;
				else {
					if (! escaping && chars[i] == '*')
						sb.append(".*");
					else
						sb.append(chars[i]);
					escaping = false;
				}
			}
			
			this.patternCache.put(op2, p = Pattern.compile(sb.toString()));
		}
			
		return p.matcher(op1.toString()).matches();
	}
	
	/**
	 * Returns this object's string representation, always &quot;LIKE&quot;.
	 */
	public String toString() {
		return "LIKE";
	}
}