
package eu.dnetlib.utils.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 (IOException ioe) {
			throw new CqlException("Error building cql parser.", ioe);
			
		} catch (RecognitionException re) {
			throw new CqlException("Error parsing cql query.", re);
			
		} catch (CqlRuntimeException cre) {
			throw new CqlException("Error parsing cql query.", cre.getCause());			
		}
	}

	/**
	 * 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();
	}
}
