/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: EjbqlSelectVisitor.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.lib.ejb21.sql;

import java.util.Map;
import java.util.Stack;

import org.ow2.jonas.deployment.ejb.ejbql.ASTAggregateSelectExpression;
import org.ow2.jonas.deployment.ejb.ejbql.ASTCmpPathExpression;
import org.ow2.jonas.deployment.ejb.ejbql.ASTEJBQL;
import org.ow2.jonas.deployment.ejb.ejbql.ASTIdentificationVariable;
import org.ow2.jonas.deployment.ejb.ejbql.ASTPath;
import org.ow2.jonas.deployment.ejb.ejbql.ASTSelectClause;
import org.ow2.jonas.deployment.ejb.ejbql.ASTSelectExpression;
import org.ow2.jonas.deployment.ejb.ejbql.ASTSingleValuedCmrPathExpression;
import org.ow2.jonas.deployment.ejb.ejbql.ASTSingleValuedPathExpression;
import org.ow2.jonas.deployment.ejb.ejbql.EJBQLConstants;
import org.ow2.jonas.deployment.ejb.ejbql.SimpleNode;

import org.objectweb.jorm.type.api.PType;
import org.objectweb.jorm.type.api.PTypeSpace;
import org.objectweb.medor.api.Field;
import org.objectweb.medor.filter.api.AggregateOperator;
import org.objectweb.medor.filter.lib.Avg;
import org.objectweb.medor.filter.lib.BasicFieldOperand;
import org.objectweb.medor.filter.lib.Count;
import org.objectweb.medor.filter.lib.Max;
import org.objectweb.medor.filter.lib.Min;
import org.objectweb.medor.filter.lib.Sum;
import org.objectweb.medor.query.api.QueryTree;
import org.objectweb.medor.query.api.QueryTreeField;
import org.objectweb.medor.query.lib.Nest;
import org.objectweb.medor.query.lib.SelectProject;

/**
 * Implementation of a visitor that creates the selection projection for
 * corresponding to a given WHERE clause. Created on Sep 6, 2002
 * @author Christophe Ney [cney@batisseurs.com]: Initial developer
 * @author Helene Joanin: Take into account the EJBQL version 2.1 syntax.
 * @author Helene Joanin: Take into account the aggregate select expression.
 */
public class EjbqlSelectVisitor extends EjbqlAbstractVisitor {

    Map fields;
    AggregateOperator aggregateOp = null;
    QueryTree qt;

    /**
     * Constructor
     * @param ejbql root of the lexical tree of the query
     * @param _fields Map with (identifier,JormExtent) pairs
     */
    public EjbqlSelectVisitor(ASTEJBQL ejbql, Map _fields, SelectProject sp) throws Exception {
        this.qt = sp;
        fields = _fields;
        visit(ejbql);
    }

    /**
     * get the query tree that was built from visiting the lexical tree. This is
     * a nest if there is an aggregate function or a select projet otherwise.
     */
    public QueryTree getQueryTree() {
        return qt;
    }

    /**
     * Visit child node. SELECT [ DISTINCT ] {select_expression | OBJECT
     * (identification_variable)}
     */
    public Object visit(ASTSelectClause node, Object data) {
        visit((SimpleNode) node, data);
        try {
            boolean distinct = node.distinct;
            qt.setDistinct(distinct);
            SelectProject sp = (SelectProject) qt;
            QueryTreeField qtf = (QueryTreeField) fields.get((String) ((Stack) data).pop());
            QueryTreeField qtf2 = sp.addPropagatedField(qtf.getName(), qtf.getType(), new QueryTreeField[] {qtf});
            //TraceEjb.query.log(BasicLevel.DEBUG, "The SelectProjectQueryTree: ");
            //QueryTreePrinter.printQueryTree(sp, TraceEjb.query, BasicLevel.DEBUG);
            if (aggregateOp != null) {
                Nest n = new Nest(new QueryTreeField[] {qtf2}, "grouped_fields", new QueryTreeField[0], "aggregate_node");
                PType type = null;
                if (aggregateOp instanceof Sum) {
                    if (qtf.getType().equals(PTypeSpace.FLOAT) || qtf.getType().equals(PTypeSpace.DOUBLE)) {
                        type = PTypeSpace.DOUBLE;
                    } else if (qtf.getType().equals(PTypeSpace.BIGINTEGER)) {
                        type = PTypeSpace.BIGINTEGER;
                    } else if (qtf.getType().equals(PTypeSpace.BIGDECIMAL)) {
                        type = PTypeSpace.BIGDECIMAL;
                    } else {
                        type = PTypeSpace.LONG;
                    }
                } else if ((aggregateOp instanceof Max) || (aggregateOp instanceof Min)) {
                    type = qtf.getType();
                } else if (aggregateOp instanceof Avg) {
                    type = PTypeSpace.DOUBLE;
                } else if (aggregateOp instanceof Count) {
                    type = PTypeSpace.LONG;
                }
                //replace the field in the aggregateOp by the propagated field
                aggregateOp.setExpression(0, new BasicFieldOperand(qtf2));
                n.addCalculatedField("calculed_field", type, aggregateOp);
                qt = n;
            }
        } catch (Exception e) {
            throw new VisitorException(e);
        }
        return null;
    }

    /**
     * Visit child node
     */
    public Object visit(ASTSelectExpression node, Object data) {
        return visit((SimpleNode) node, data);
    }

    /**
     * Visit child node
     */
    public Object visit(ASTAggregateSelectExpression node, Object data) {
        visit((SimpleNode) node, data);
        Stack s = (Stack) data;
        int operator = ((Integer) node.ops.get(0)).intValue();
        boolean distinct = node.distinct;
        Field field = (Field) fields.get((String) s.peek());
        BasicFieldOperand fieldOp = new BasicFieldOperand(field);
        switch (operator) {
            case EJBQLConstants.AVG:
                aggregateOp = new Avg(fieldOp, distinct);
                break;
            case EJBQLConstants.COUNT:
                aggregateOp = new Count(fieldOp, distinct);
                break;
            case EJBQLConstants.MAX:
                aggregateOp = new Max(fieldOp, distinct);
                break;
            case EJBQLConstants.MIN:
                aggregateOp = new Min(fieldOp, distinct);
                break;
            case EJBQLConstants.SUM:
                aggregateOp = new Sum(fieldOp, distinct);
                break;
            default:
                throw new Error("AggregateOperator '" + operator + "' unknown");
        }
        return null;
    }

    /**
     * Visit child node
     */
    public Object visit(ASTCmpPathExpression node, Object data) {
        return visit((SimpleNode) node, data);
    }

    /**
     * Visit child node
     */
    public Object visit(ASTSingleValuedCmrPathExpression node, Object data) {
        return visit((SimpleNode) node, data);
    }

    /**
     * Visit child node
     */
    public Object visit(ASTSingleValuedPathExpression node, Object data) {
        return visit((SimpleNode) node, data);
    }

    /**
     * Push the Node to the stack
     */
    public Object visit(ASTIdentificationVariable node, Object data) {
    	// Identification variables are case insensitive
    	String vName = ((String) node.value).toLowerCase();
        ((Stack) data).push(vName + "." + Field.PNAMENAME);
        return null;
    }

    /**
     * Push the Node to the stack
     */
    public Object visit(ASTPath node, Object data) {
        ((Stack) data).push(node.value);
        return null;
    }
}