/**
 * 
 */
package gr.uoa.di.driver.cql;

import java.io.IOException;
import java.io.StringReader;

import org.antlr.runtime.ANTLRReaderStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;

/**
 * @author stoumpos
 *
 */
public class Cql {
	
	/**
	 * Parse cql query in <code>text</code> and return the respective
	 * cql query object.
	 * 
	 * @param text	The cql text.
	 * @return	The cql tree object.
	 */
	public static CqlQuery parse(String text) throws CqlException {
	
		try {
			StringReader reader= new StringReader(text);
			ANTLRReaderStream input = new ANTLRReaderStream(reader);
			CqlLexer lexer = new CqlLexer(input);
		    CommonTokenStream tokens = new CommonTokenStream(lexer);
		    CqlParser parser = new CqlParser(tokens);
		    
		    CqlQuery query = parser.cql().query;

		    return query;
		    
		} catch (RecognitionException re) {
			throw new CqlException("Error parsing cql query.", re);
			
		} catch (IOException ioe) {
			throw new CqlException("Error building cql parser.", ioe);
		}
	}
	
	/**
	 * Writes <code>query</code> as string. The same functionality is
	 * possible through {@link CqlQuery#toString()}. 
	 * 
	 * @param query
	 * @return
	 */
	public static String encode(CqlQuery query) {
		return query.toString();
	}
	
	
	public static void main(String[] args) throws CqlException {
        String text = "foo or and and bar=\"goo=\\\"fff\\\" \" and ((a or (b)))";
		text = "(t=a and t=b) or ((t=c) and (t=d))";
		
		System.out.println("query text : " + text);
		
		CqlQuery query = Cql.parse(text);
		
		System.out.println("parsed query : " + query);
	}	
}
