/* ====================================================================
 * 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/>.
 */
/*
 * GenericMVCAction.java
 *
 * Created on January 29, 2003, 2:56 PM
 */
package org.apache.jetspeed.modules.actions.portlets;

import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.portal.PortletInstance;
import org.apache.jetspeed.portal.portlets.GenericMVCContext;
import org.apache.jetspeed.portal.portlets.GenericMVCPortlet;
import org.apache.jetspeed.services.persistence.PersistenceManager;
import org.apache.jetspeed.services.persistence.PortalPersistenceException;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.util.PortletSessionState;

import org.apache.turbine.util.Log;
import org.apache.turbine.util.RunData;

import org.apache.velocity.context.Context;


/**
 * Provides standard portal and MVC related action functionality.  Developers
 * extend this class for thier own actions and provide implementations of the
 * build*Context methods apropos to thier portlet needs.
 *
 * @author  tkuebler
 * @version $Id: GenericMVCAction.java,v 1.8 2003/02/11 23:09:17 tkuebler Exp $
 * @stereotype moment-interval
 */
public class GenericMVCAction
    extends PortletAction
  {

    /** Creates a new instance of GenericMVCAction */
    public GenericMVCAction()
      {

        // remove if empty at end of design phase
      }

    // override what you need to here
    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 = new GenericMVCContext();
                rundata.getTemplateInfo().setTemplateContext("VelocityActionContext", context);
              }

            try
              {

                // process implicit ActionEvent invocation
                Log.debug("Action: try executing events");

                GenericMVCPortlet portlet = (GenericMVCPortlet) 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);
              }
          }
      }

    public void doPerform(RunData rundata, Context context)
                   throws Exception
      {

        GenericMVCPortlet portlet = null;
        JetspeedRunData jdata = (JetspeedRunData) rundata;
        Log.debug("GenericMVCAction: retrieved context: " + context);

        if (context != null)
          {
            portlet = (GenericMVCPortlet) context.get("portlet");
          }

        Log.debug("GenericMVCAction: 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("GenericMVCAction: building customize");
                buildConfigureContext(portlet, context, rundata);

                return;
              }

            // we're maximized
            if (jdata.getMode() == jdata.MAXIMIZE)
              {
                Log.debug("GenericMVCAction: building maximize");
                buildMaximizedContext(portlet, context, rundata);

                return;
              }

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

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

        // code goes here. :)
      }

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

    /**
     * Convenience method for retreiving this action's PortletInstance
     * @param Context context Current context object.
     * @return Portlet the Portlet for this action
     * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
     */
    public PortletInstance getPortletInstance(Context context)
    {
        return getPortlet(context).getInstance((RunData) context.get("data"));
    }
    
    /**
    * Convenience method for retreiving this action's PortletInstance
    * attribute.
    * @param String Attribute Name
    * @param Context context Current context object.
    * @return String portlet attribute
    * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
    */   
    public String getAttribute(String attrName, Context context)
    {
        return getPortletInstance(context).getAttribute(attrName);
    }
    
    /**
    * Convenience method for retreiving this action's PortletInstance
    * attribute.
    * @param String Attribute Name
    * @param String Default to return if no attribute is found
    * @param Context context Current context object.
    * @return String portlet attribute
    * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
    */
    public String getAttribute(String attrName, String defaultValue, Context context)
    {
        return getPortletInstance(context).getAttribute(attrName, defaultValue);
    }
    /**
    * Convenience method for setting this action's PortletInstance
    * attribute.
    * @param String Attribute Name
    * @param String Attribute Value
    * @param Context context Current context object.
    * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
    */
    public void setAttribute(String attrName, String value, Context context)
        throws PortalPersistenceException
    {
        PortletInstance instance = getPortletInstance(context);
        instance.setAttribute(attrName, value);
        PersistenceManager.store(instance);
    }
  }
