/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package eu.espas.cql.trans;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.apache.log4j.Logger;
import org.z3950.zing.cql.CQLNode;
import org.z3950.zing.cql.CQLParseException;
import org.z3950.zing.cql.CQLParser;

/** 
 *
 * @author George Athanasopoulos <george.athanasopoulos at gmail.com, UoA | ARC>
 */
public class TransformationEngine {
    
    private static final Logger _logger = Logger.getLogger(TransformationEngine.class);
    
    private CQLParser cqlParser;

    private TransformationVisitor visitor;

    public TransformationEngine(TransformationVisitor visitor) {
        this.visitor = visitor;
        cqlParser = new CQLParser();
    }
    
    public String getQueryClause(String cqlExpression) throws CQLProcessingException{
        visitor.clearVisitor();
        String result = visitor.prepareQueryExpression(this.getConstraintClause(cqlExpression));
        return result;
    }
    
    public String getConstraintClause(String cqlExpression) throws CQLProcessingException {
        visitor.clearVisitor();
        String result;
        
        StringReader reader = new StringReader(cqlExpression);
        try {
//            extract the CQL expression tree
            CQLNode expressionRoot = parseExpression(reader);
            result = visitor.visitExpression(expressionRoot);
            result = visitor.prepareConstraintExpression(result);
        } catch (Exception ex) {
//            _logger.error("Exception while parsing CQL expression :" + cqlExpression, ex);

			throw new CQLProcessingException("Error parsing cql", ex);
        }

        return result;
    }
    
    private CQLNode parseExpression(Reader expressionReader) throws CQLParseException, IOException{
        CQLNode result  = cqlParser.parse(expressionReader);
        return result;
    }
}