package eworks.eRQL.engine;

import java.io.*;
import eworks.RQL.engine.RqlEngine;
import eworks.eRQL.model.Value;
import eworks.eRQL.parser.scanner;
import java_cup.runtime.*;

/**
 * <p><code>eRqlEngine</code> is a prototype implementation of an <em>eRQL</em> processor -
 * a new query language for RDF.
 * Details on <em>eRQL</em> can be obtained at 
 * <a href="http://www.dbis.informatik.uni-frankfurt.de/~tolle/RDF/eRQL/" target="_blank">http://www.dbis.informatik.uni-frankfurt.de/~tolle/RDF/eRQL/</a>
 * and
 * <a href="http://www.wleklinski.de/rdf/" target="_blank">http://www.wleklinski.de/rdf/</a>.
 * Details on RDF are available at
 * <a href="http://www.w3.org/RDF/" target="_blank">http://www.w3.org/RDF/</a>.</p>
 * 
 * <pre>
 *eRqlEngine eRQL = new eRqlEngine();
 *eworks.RDF.model.Tuples result = null;
 *try {
 *    result=eRQL.query(new java.io.File("C:\input.rdf"),"~~ Pablo Picasso");
 *} catch(Exception e) {
 *    System.out.println(e);
 *}
 *</pre>
 * 
 * @author Fabian Wleklinski (<a href="mailto:fabian@wleklinski.de">fabian@wleklinski.de</a>)
 * @version 1.00 (2003-11-03)
 */
public class eRqlEngine {
	
	/**
	 * Output stream for printing error- and debug-messages.
	 */
	private java.io.OutputStream output = null;

	/**
	 * Constructs an eRqlEngine-instance and sets the output-stream
	 * for printing error- and debug-messages.
	 * 
	 * @param output Output-stream for printing error- and debug-messages.
	 */	
	public eRqlEngine( java.io.OutputStream output ) {
		this.output = output;
	}
	
	/**
	 * Constructs an eRqlEngine-instance.
	 */	
	public eRqlEngine() {
	}
	
	/**
	 * Evaluates the eRQL query <code>queryString</code>.
	 * 
	 * @param rdfFile The RDF file to query.
	 * @param queryString The query string to query.
	 * @return The tuples that match the query.
	 */
	public eworks.RDF.model.Tuples query(java.io.File rdfFile, String queryString) throws Exception {
		
		StringReader sr = new StringReader( queryString );
		
		scanner s = new scanner( sr );
		
		eworks.eRQL.parser.parser p = new eworks.eRQL.parser.parser( s );
		Symbol parse_tree = null;
		try {
			parse_tree = p.parse();
		} catch( Exception e ) {
			System.out.println( e );
			throw(e);
		}
		
		if (! (parse_tree.value instanceof eworks.eRQL.model.Value))
			throw new Exception("parse_tree is null!");
		Value query = (eworks.eRQL.model.Value) parse_tree.value;

		// DEBUGOUT
		System.out.println();
		System.out.println("eworks.eRQL.engine.eRqlEngine.query()");
		System.out.println("-------------------------------------");
		System.out.println( "\t     Query:\t" + queryString );
		System.out.println( "\tQuery-Tree:\t" + query.toString() );

		query = query.compact();

		// DEBUGOUT
		System.out.println( "\t (reduced):\t" + query.toString() );
		System.out.println();
		
		RqlEngine rqlEngine = new RqlEngine();
		rqlEngine.setDataSource(rdfFile);

		eworks.RDF.model.Tuples result = query.query(rqlEngine);

		return result;
	}
}