/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the "License").  You may not use this file except 
 * in compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt or 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html. 
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * HEADER in each file and include the License file at 
 * glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable, 
 * add the following below this CDDL HEADER, with the 
 * fields enclosed by brackets "[]" replaced with your 
 * own identifying information: Portions Copyright [yyyy] 
 * [name of copyright owner]
 */
// Copyright (c) 1998, 2006, Oracle. All rights reserved.  
package oracle.toplink.essentials.internal.parsing;

import oracle.toplink.essentials.queryframework.*;
import oracle.toplink.essentials.internal.sessions.AbstractSession;

/**
 * INTERNAL
 * <p><b>Purpose</b>: This represents an EJBQL parse tre
 * <p><b>Responsibilities</b>:<ul>
 * <li> Maintain the context for the expression generation
 * <li> Build an initial expression
 * <li> Return a reference class for the expression
 * <li> Maintain the root node for the query
 * </ul>
 *    @author Jon Driscoll and Joel Lucuik
 *    @since TopLink 4.0
 */
public class EJBQLParseTree extends ParseTree {

    /**
     * EJBQLParseTree constructor comment.
     */
    public EJBQLParseTree() {
        super();
    }

    /**
     * INTERNAL
     * Build the context to be used when generating the expression from the parse tree
     */
    public GenerationContext buildContext(ReadQuery readQuery, AbstractSession session) {
        GenerationContext contextForGeneration = super.buildContext(readQuery, session);

        contextForGeneration.setBaseQueryClass(readQuery.getReferenceClass());
        return contextForGeneration;
    }

    /**
     * INTERNAL
     * Build the context to be used when generating the expression from the
     * subquery parse tree.
     */
    private GenerationContext buildSubqueryContext(ReadQuery readQuery, GenerationContext outer) {
        GenerationContext context = new SelectGenerationContext(outer, this);
        context.setBaseQueryClass(readQuery.getReferenceClass());
        return context;
    }

    /**
     * Add all of the relevant query settings from an EJBQLParseTree to the given
     * database query.
     * @param query The query to populate
     * @param outer the GenerationContext of the outer EJBQL query.
     * @return the GenerationContext for the subquery
     */
    public GenerationContext populateSubquery(ObjectLevelReadQuery readQuery, GenerationContext outer) {
        GenerationContext innerContext = buildSubqueryContext(readQuery, outer);
        populateReadQueryInternal(readQuery, innerContext);
        return innerContext;
    }
    
    /**
     * Add all of the relevant query settings from an EJBQLParseTree to the given
     * database query.
     * @param query The query to populate
     * @param session The sessionto use to information such as descriptors.
     */
    public void populateQuery(DatabaseQuery query, AbstractSession session) {
        if (query.isObjectLevelReadQuery()) {
            ObjectLevelReadQuery objectQuery = (ObjectLevelReadQuery)query;

            GenerationContext generationContext = buildContext(objectQuery, session);

            populateReadQueryInternal(objectQuery, generationContext);
            
        } else if (query.isUpdateAllQuery()) {
            UpdateAllQuery updateQuery = (UpdateAllQuery)query;

            GenerationContext generationContext = buildContext(updateQuery, session);

            // Apply the query node to the query (this will be an UpdateNode for a read query)
            applyQueryNodeToQuery(updateQuery, generationContext);
            if (updateQuery.getReferenceClass() == null) {
                // Adjust the reference class if necessary
                adjustReferenceClassForQuery(updateQuery, generationContext);
            }
            updateQuery.setSession(session);
            addUpdatesToQuery(updateQuery, generationContext);

            setSelectionCriteriaForQuery(updateQuery, generationContext);
        } else if (query.isDeleteAllQuery()) {
            DeleteAllQuery deleteQuery = (DeleteAllQuery)query;

            GenerationContext generationContext = buildContext(deleteQuery, session);

            // Apply the query node to the query (this will be an DeleteNode)
            applyQueryNodeToQuery(deleteQuery, generationContext);
            if (deleteQuery.getReferenceClass() == null) {
                // Adjust the reference class if necessary
                adjustReferenceClassForQuery(deleteQuery, generationContext);
            }
            deleteQuery.setSession(session);            

            setSelectionCriteriaForQuery(deleteQuery, generationContext);
        }
    }

    private void populateReadQueryInternal(ObjectLevelReadQuery objectQuery, 
                                           GenerationContext generationContext) {
        // Get the reference class if it does not exist.  This is done
        // for dynamic queries in EJBQL 3.0
        if (objectQuery.getReferenceClass() == null) {
            // Adjust the reference class if necessary
            adjustReferenceClassForQuery(objectQuery, generationContext);
        }

        // Initialize the base expression inthe generation context
        initBaseExpression(objectQuery, generationContext);
        
        // Validate parse tree
        validate(generationContext.getSession(), getClassLoader());

        // Apply the query node to the query (this will be a SelectNode for a read query)
        applyQueryNodeToQuery(objectQuery, generationContext);
        
        // Verify the SELECT is valid (valid alias, etc)
        verifySelect(objectQuery, generationContext);
        
        // This is what it's all about...
        setSelectionCriteriaForQuery(objectQuery, generationContext);
        
        // Add any ordering
        addOrderingToQuery(objectQuery, generationContext);

        // Add any grouping
        addGroupingToQuery(objectQuery, generationContext);
        
        // Add having
        addHavingToQuery(objectQuery, generationContext);
        
        // Add non fetch joined variables
        addNonFetchJoinAttributes(objectQuery, generationContext);
    }

}
