/* ====================================================================
 * 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;

// Java stuff
import java.lang.reflect.Method;
import java.util.Enumeration;

// Jetspeed stuff
import org.apache.jetspeed.portal.Portlet;
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.util.ParameterParser;
import org.apache.jetspeed.modules.actions.JspAction;


/**
 * An abstract action class to build JspPortlet 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:morciuch@apache.org">Mark Orciuch</a>
 *
 * @version $Id: JspPortletAction.java,v 1.2 2002/09/27 20:46:15 morciuch Exp $
 */
public abstract class JspPortletAction extends JspAction
{

    /**
     * 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)
    {
        data.getRequest().setAttribute("template", template);
    }

    /**
     * Performs the action
     * 
     * @param rundata
     * @exception Exception
     */
    public void doPerform(RunData rundata)
    throws Exception
    {
        Portlet portlet = (Portlet) rundata.getRequest().getAttribute("portlet");
        JetspeedRunData jdata = (JetspeedRunData) rundata;

        if (Log.getLogger().isDebugEnabled())
        {
            Log.debug("JspPortletAction: retrieved portlet: " + portlet);        
        }
        if (portlet != null)
        {
            // we're bein configured
            if ((jdata.getMode() == jdata.CUSTOMIZE) 
                && (portlet.getName().equals(jdata.getCustomized().getName())))
            {
                if (Log.getLogger().isDebugEnabled())
                {
                    Log.debug("JspPortletAction: building customize");
                }
                buildConfigureContext(portlet, rundata);
                return;
            }

            // we're maximized
            if (jdata.getMode() == jdata.MAXIMIZE)
            {
                if (Log.getLogger().isDebugEnabled())
                {
                    Log.debug("JspPortletAction: building maximize");
                }
                buildMaximizedContext(portlet, rundata);
                return;
            }

            if (Log.getLogger().isDebugEnabled())
            {
                Log.debug("JspPortletAction: building normal");
            }
            buildNormalContext(portlet, rundata);
        }
    }

    /**
     * This method should be called to execute the event based system.
     *
     * @param data Turbine information.
     * @exception Exception a generic exception.
     */
    public void executeEvents(RunData data)
    throws Exception
    {
        // Name of the button.
        String theButton = null;

        // Parameter parser.
        ParameterParser pp = data.getParameters();

        // The arguments to pass to the method to execute.
        Object[] args = new Object[2];

        // The arguments to the method to find.
        Class[] classes = new Class[2];
        classes[0] = RunData.class;
        classes[1] = Portlet.class;

        String button = pp.convert(BUTTON);

        // Loop through and find the button.
        for (Enumeration e = pp.keys() ; e.hasMoreElements() ;)
        {
            String key = (String) e.nextElement();
            if (key.startsWith(button))
            {
                theButton = formatString(key);
                break;
            }
        }
        // Portlet context
        Portlet portlet = (Portlet) data.getRequest().getAttribute("portlet");        

        // Ignore submits from other instances of the same portlet
        if (theButton == null || !PortletSessionState.isMyRequest(data, portlet))
        {
            throw new NoSuchMethodException("JspActionEvent: The button was null or not my request");
        }

        Method method = getClass().getMethod(theButton, classes);
        args[0] = data;
        args[1] = portlet;
        method.invoke(this, args);
    }

    /** 
     * 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(Portlet portlet, RunData rundata)
    throws Exception
    {
        buildNormalContext(portlet, 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(Portlet portlet, 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(Portlet portlet, RunData rundata)
    throws Exception;

}
