/* ====================================================================
 * 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/>.
 */
/*
 * GenericMVCPortlet.java
 *
 * Created on January 27, 2003, 5:10 PM
 */
package org.apache.jetspeed.portal.portlets;

import javax.servlet.http.HttpServletRequest;

import org.apache.ecs.ConcreteElement;

import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.portal.PortletException;
import org.apache.jetspeed.portal.portlets.viewprocessor.*;
// using the * form due to the puggable nature
//ie no recompile to support new view processors
import org.apache.jetspeed.util.PortletSessionState;
import org.apache.jetspeed.util.template.JetspeedLink;
import org.apache.jetspeed.util.template.JetspeedTemplateLink;

import org.apache.turbine.modules.ActionLoader;
import org.apache.turbine.services.pull.TurbinePull;
import org.apache.turbine.util.Log;
import org.apache.turbine.util.RunData;

/**
 * Provides the basic MVC Portlet functionality independant of any
 * specific view technology (ie jsp, velocity, xslt, etc).  It handles
 * the views via a ViewProcessor, which is a pluggable, factory
 * created, run time module for which ever view technology your portlet
 * uses.
 *
 * There is no need to extend this portlet class, just define your porlet
 * entry in the registy as a child of this class and provide your template
 * and action class (extened from GenericMVCAction of course) and you
 * are good to go.
 *
 * Example .xreg entry:
 *
 *  <portlet-entry name="GenericMVCPortlet" hidden="false"
 *       type="abstract" application="false">
 *       <security-ref parent="default"/>
 *       <classname>com.cisco.it.psf.portal.portlets.GenericMVCPortlet</classname>
 *      <media-type ref="html"/>
 *      <url cachedOnURL="true"/>
 *  </portlet-entry>
 *  <portlet-entry name="VelocityMVCExample" hidden="false" type="ref"
 *      parent="GenericMVCPortlet" application="false">
 *      <meta-info>
 *          <title>Velocity MVC Portlet</title>
 *          <description>Velocity Generic MVC Portlet</description>
 *      </meta-info>
 *      <classname>com.cisco.it.psf.portal.portlets.GenericMVCPortlet</classname>
 *      <parameter name="template" value="mvc-example" hidden="true"
 *          cachedOnName="true" cachedOnValue="true"/>
 *      <parameter name="viewtype" value="Velocity" hidden="true"
 *          cachedOnName="true" cachedOnValue="true"/>
 *      <parameter name="action"
 *          value="portlets.ExampleGenericMVCAction" hidden="true"
 *          cachedOnName="true" cachedOnValue="true"/>
 *      <url cachedOnURL="true"/>
 *  </portlet-entry>
 *
 * See the Velocity and JSP MVC Portlet examples for template and action class clues.
 *
 * To add new view processor types, simply implement the ViewProcessor
 * interface and add your type into the <b>viewprocessor.properties</b> file as 
 * shown in the example below:
 *
 * mvc.viewprocessor.Velocity = org.apache.jetspeedportlets.viewprocessors.VelocityViewProcessor
 * mvc.viewprocessor.JSP = org.apache.jetspeedportlets.viewprocessors.JSPViewProcessor
 * mvc.viewprocessor.XSL = org.apache.jetspeedportlets.viewprocessors.XSLViewProcessor
 *
 * @author  tkuebler
 * @author <a href="mailto:weaver@apache.org">Scott T. Weaver</a>
 * @version $Id: GenericMVCPortlet.java,v 1.11 2003/02/11 23:09:18 tkuebler Exp $
 * @stereotype role
 */
public class GenericMVCPortlet extends AbstractInstancePortlet
{
	// STW: Context keys
	public static final String PORTLET = "portlet";
	public static final String TEMPLATE = "template";
	public static final String RUNDATA = "data";
	public static final String PORTLET_CONFIG = "conf";
	public static final String SKIN = "skin";
	public static final String VIEW_TYPE = "viewType";
	
	

    // need cache timer, etc
    private String viewType = "ERROR: not set in config";
    private String actionName = "ERROR: not set in config";
    private String template = "ERROR: not set in config";
    private String configureTemplate;
    private String maximizedTemplate;
    private ViewProcessor processor = null;
    private boolean providesCustomization;

    public void init() throws PortletException
    {

        //STW: Added caching setUp  
        if (isCacheable())
        {
            try
            {
                setExpirationMillis(
                    Long.parseLong(
                        getPortletConfig().getInitParameter("cache-period-milliseconds", "0")));
            }
            catch (NumberFormatException e)
            {
                setExpirationMillis(0);
            }
        }
        
        //STW: check custimization attribute
        String provConf = getPortletConfig().getInitParameter("provides.customization", "false");
        providesCustomization = new Boolean(provConf).booleanValue();
        
        // pull the important info out of the portlet config
        actionName = getPortletConfig().getInitParameter("action");
        // STW: Allow subclasses to set viewtype for backward compatibillity
        if (getPortletConfig().getInitParameter("viewtype") != null)
        {
            viewType = getPortletConfig().getInitParameter("viewtype");
        }

        template = getPortletConfig().getInitParameter("template");

        // get viewprocessor from factory
        Log.info(
            "GenericMVCPortlet - creating view processor for viewtype = "
                + viewType
                + ", template = "
                + template);
        processor = ViewProcessorFactory.getViewProcessor(viewType);

        // initialize view processor with portlet info
        processor.init(this);

        // should make this config file driven
        // STW removed this so subclasses can decide this for
        // themselves.
        // setCacheable(false);
    }

/**
 * Whether or not this portlet provides it's own customizer.
 * This can be set at the registry level by adding a 
 * boolean paramter "provides.customization"
 * Defaults to "false"
 */
    public boolean providesCustomization()
    {
        return providesCustomization;
    }

    public ConcreteElement getContent(RunData rundata)
    {

        //if caching is turned off or no expiration time set, generate and return the content
        if (!isCacheable() || null == getExpirationMillis())
        {
            return buildContent(rundata);
        }

        //is the cached content still valid, if not, generate and return the content
        if (getExpirationMillis().longValue() <= System.currentTimeMillis())
        {
            return buildContent(rundata);
        }

        //else, the cached content is fine to be returned
        return getContent(rundata, null, true);

    }

    protected ConcreteElement buildContent(RunData rundata)
    {
        // create a new context
        // populate it with data
        GenericMVCContext context = new GenericMVCContext(TurbinePull.getGlobalContext());
        context.put(RUNDATA, rundata);
        context.put(PORTLET, this);
        context.put(PORTLET_CONFIG, this.getPortletConfig());
        context.put(SKIN, this.getPortletConfig().getPortletSkin());
        context.put(TEMPLATE, getCurrentTemplate(rundata));
        context.put(VIEW_TYPE, viewType);
        populateRequest(rundata);

        // put references to the pull tools in the context
        TurbinePull.populateContext(context, rundata);
        // Initialize jlink and jslink tools with ourselves
        // to enable links between portlets
        Object jlink = context.get("jlink");

        if (jlink instanceof JetspeedTemplateLink)
        {
            ((JetspeedTemplateLink) jlink).setPortlet(this);
        }

        Object jslink = context.get("jslink");

        if (jslink instanceof JetspeedLink)
        {
            ((JetspeedLink) jslink).setPortlet(this);
        }

        // Handle Action
        if (actionName != null)
        {

            try
            {

                // store the context so that the action can retrieve it
                //Log.debug("VelocityPortlet found action "+actionName+" context "+context);
                // note: the name it is stored under is legacy, leaving it this way
                // because some of the routines fall back to old default behavior
                // of the velocity portlet and might depend on the name
                rundata.getTemplateInfo().setTemplateContext("VelocityPortletContext", context);

                if (Log.getLogger().isDebugEnabled())
                {
                    Log.debug(
                        "GenericMVCPortlet: Executing action ["
                            + actionName
                            + "] for portlet ["
                            + this.getName()
                            + "]");
                }

                ActionLoader.getInstance().exec(rundata, actionName);
            }
            catch (Exception e)
            {
                Log.error("GenericMVCPortlet - error executing action" + e);
                e.printStackTrace();
            }
        }

        // Process View
        // call processView method
        Log.info("GenericMVCPortlet - calling processView on processor");

        ConcreteElement result = (ConcreteElement) processor.processView(context);
        Log.info("GenericMVCPortlet - setting this portlet's content");
        clearContent();
        setContent(result); // only needed when caching is true I believe

        // return result
        return result;
    }
    /**
     * @see setViewType()
     * @return String
     */
    protected String getViewType()
    {
        return viewType;
    }

    /**
    * STW: Added for backward compatibility when using this
     * class to subclass the existing Jsp and Velocity portlets
     * so they can set their view prior to super.init();
     * @param viewType The viewType to set
     */
    protected void setViewType(String viewType)
    {
        this.viewType = viewType;
    }

    /**
     * This is called before any action execution happens.
     * This provides backward compatibility to JspPortletActions
     * who retreive  information, like Portlet, from the request
     * BEFORE the ViewProcessor.processView() is called
     * which normally populates the request with Context objects.
     * @author <a href="mailto:sweaver@rippe.com">Scott Weaver</a>
     */
    protected void populateRequest(RunData rundata)
    {
        HttpServletRequest request = rundata.getRequest();
        request.setAttribute("data", rundata);
        request.setAttribute("portlet", this);
        request.setAttribute("conf", this.getPortletConfig());
        request.setAttribute("skin", this.getPortletConfig().getPortletSkin());
        request.setAttribute("template", getCurrentTemplate(rundata));
        request.setAttribute("viewType", viewType);
    }
    
    /**
     * 
     */
    protected String getCurrentTemplate( RunData data)
    {
    	String useTemplate = (String) PortletSessionState.getAttribute(this, data, TEMPLATE);
    	if(useTemplate == null)
    	{
    		useTemplate = this.template;
    	}
    	
    	return useTemplate;
    }
}
