/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2000-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *     "Apache Jetspeed" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache" or
 *    "Apache Jetspeed", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
 
package org.apache.jetspeed.modules.actions.portlets;

import org.apache.jetspeed.portal.portlets.VelocityPortlet;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.util.PortletSessionState;

// Turbine stuff
import org.apache.turbine.util.Log;
import org.apache.turbine.util.RunData;
import org.apache.turbine.services.velocity.TurbineVelocity;
import org.apache.turbine.modules.Action;
import org.apache.turbine.modules.actions.VelocityAction;

// Velocity Stuff
import org.apache.velocity.context.Context;


/**
 * An abstract action class to build VelocityPortlet actions.
 * 
 * <p>Don't call it from the URL, the Portlet and the Action are automatically
 * associated through the registry PortletName
 * 
 * @author <a href="mailto:raphael@apache.org">Raphaël Luta</a>
 * @author <a href="mailto:re_carrasco@bco011.sonda.cl">Roberto Carrasco</a>
 *
 * @version $Id: VelocityPortletAction.java,v 1.10 2002/09/30 20:35:36 morciuch Exp $
 */
public abstract class VelocityPortletAction extends VelocityAction
{

    /**
     * This overrides the default Action.perform() to execute the
     * doEvent() method.  If that fails, then it will execute the
     * doPerform() method instead.
     *
     * @param data A Turbine RunData object.
     * @exception Exception, a generic exception.
     */
    protected void perform( RunData rundata )
        throws Exception
    {
        Context context = getContext(rundata);
        if ((context!=null)&&(rundata.getParameters().getString("action")!=null))
        {
            // if context is already defined and Actions defined, events 
            // have already been processed, call doPerform
            Log.debug("Action detected with action + context");
            doPerform(rundata, context);
        }
        else
        {
            // if context is null, create a new one
            if (context==null)
            {
                Log.debug("Action: building action context");
                context = TurbineVelocity.getContext();
                rundata.getTemplateInfo().setTemplateContext("VelocityActionContext",context);
            }

            try
            {
                // process implicit ActionEvent invocation
                Log.debug("Action: try executing events");
                
                VelocityPortlet portlet = (VelocityPortlet) context.get("portlet");
                
                if (portlet != null)
                {
                	// verify this portlet is the one requested by checking the 
                	// js_peid request var.  If there is no js_peid
                	// do not worry a about verifing.  helps with backward compat.
                    if (rundata.getParameters().getString("js_peid") == null
                        || PortletSessionState.isMyRequest(rundata, portlet))
                    {
                        executeEvents(rundata, context);
                    }
                    else
                    {
                        Log.debug("Action: calling doPerform");
                        doPerform(rundata, context);
                    }
                }
                else
                {
                    executeEvents(rundata, context);
                }
               
            }                    
            catch (NoSuchMethodException e)
            {
                // no event selected, process normal context generation
                Log.debug("Action: calling doPerform");
                doPerform(rundata, context);
            }
        }
    }

    /**
     * This method is used when you want to short circuit an Action
     * and change the template that will be executed next.
     *
     * @param data Turbine information.
     * @param template The template that will be executed next.
     */
    public void setTemplate(RunData data,
                            String template)
    {
        getContext(data).put( "template" , template );
    }

    /**
     * Return the Context needed by Velocity.
     *
     * @param RunData data
     * @return Context, a context for web pages.
     */
    protected Context getContext(RunData data)
    {
        return (Context)data.getTemplateInfo()
                            .getTemplateContext( "VelocityPortletContext" );
    }

    public void doPerform( RunData rundata, Context context )
        throws Exception
    {
        VelocityPortlet portlet = null;
        JetspeedRunData jdata = (JetspeedRunData)rundata;
        
        Log.debug("VelocityAction: retrieved context: "+context);
        if (context != null)
            portlet = (VelocityPortlet)context.get( "portlet" );

        Log.debug("VelocityAction: retrieved portlet: "+portlet);
        if (portlet != null)
        {
            //System.out.println("class = " + this.getClass().getName());
            //rundata.getUser().setTemp(this.getClass().getName(), portlet.getID());

            // we're bein configured
            if  ( ( jdata.getMode()==jdata.CUSTOMIZE ) 
                && (portlet.getName().equals(jdata.getCustomized().getName())) )
            {
                Log.debug("VelocityAction: building customize");
                buildConfigureContext( portlet, context, rundata);
                return;
            }
            
            // we're maximized
            if ( jdata.getMode()==jdata.MAXIMIZE )
            {
                Log.debug("VelocityAction: building maximize");
                buildMaximizedContext( portlet, context, rundata);
                return;
            }

            Log.debug("VelocityAction: building normal");
            buildNormalContext( portlet, context, rundata);
        }        
    }

    /**
     * Helper function for actions to get the portlet id.
     * Since actions are called before portal aggregation, the ids aren't available.
     * This function will fail on the very first aggregation for a session.
     *
     * @param data Turbine information.
     * @param template The template that will be executed next.
     */
     /*
    public String getPortletID(RunData rundata)
    {
       System.out.println("get portlet id class = " + this.getClass().getName());

        return (String)rundata.getUser().getTemp(this.getClass().getName());
    }
       */

    /** 
     * Subclasses should override this method if they wish to
     * build specific content when maximized. Default behavior is
     * to do the same as normal content.
     */
    protected void buildMaximizedContext( VelocityPortlet portlet, 
                                          Context context,
                                          RunData rundata )
        throws Exception
    {
        buildNormalContext( portlet, context, rundata);
    }

    /** 
     * Subclasses should override this method if they wish to
     * provide their own customization behavior.
     * Default is to use Portal base customizer action
     */
    protected void buildConfigureContext( VelocityPortlet portlet, 
                                          Context context,
                                          RunData rundata )
        throws Exception
    {

        //FIXME: call the default CustomizePortlet action when written
    }

    /** 
     * Subclasses must override this method to provide default behavior 
     * for the portlet action
     */
    protected abstract void buildNormalContext( VelocityPortlet portlet, 
                                                Context context,
                                                RunData rundata )
        throws Exception;

}
