package com.siemens.scr.se.healthcareportal.portlets;

// Servlet and JSP stuff
import javax.servlet.http.HttpServletRequest;

// Turbine util
import org.apache.turbine.util.RunData;
import org.apache.turbine.util.Log;
import org.apache.turbine.services.TurbineServices;
import org.apache.turbine.services.jsp.JspService;
import org.apache.turbine.modules.ActionLoader;

// Jetspeed portal
import org.apache.jetspeed.portal.Portlet;
import org.apache.jetspeed.portal.portlets.AbstractPortlet;
import org.apache.jetspeed.portal.PortletException;
import org.apache.jetspeed.portal.PortletConfig;
import org.apache.jetspeed.services.TemplateLocator;
import org.apache.jetspeed.services.rundata.JetspeedRunData;
import org.apache.jetspeed.util.template.PortletTemplateLink;

// Ecs 
import org.apache.ecs.ConcreteElement;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;


/**
 * The same as the standard JSP portlet but two changes:
 * 1. I added the method <code>buildContext()</code>, which 
 * allowes to set some parameters before the JSP page is
 * executed. These parameters are supposed to be used inside
 * of this JSP page. <BR>
 * 2. I added the functionality to execute an action object.
 * 
 * @author <a href="mailto:jetspeed@wimmisoft.de">Matthias Wimmer</a> */
public class MyJSPPortlet extends AbstractPortlet {

    /** By default the data is non cacheable */
    public void init() throws PortletException {
        setCacheable( false );
    }

    /** Allows subclasses to publish their variables before the 
     *  JSP page is executed. To do that, subclasses are supposed 
     *  to override this method.*/
    public void buildContext( RunData rundata, HttpServletRequest req ) {
    }

    public ConcreteElement getContent( RunData rundata ) {
	String result = "";
        String template = "";
	JetspeedRunData jrundata = (JetspeedRunData)rundata;

        try {
            // gets the jsp page from the xreg configuration
            // NOTE: wouldn't it be better to get the param from the PSML?
            //
            template = getPortletConfig().getInitParameter( "template" );
	    //System.out.println( "Try to get the template ("+template+") from the user..." );
	    //template = (()jrundata.getProfile().getDocument().getEntry( getName() ))
            //      	                       .getParameter( "template" ).getValue();
         
            JspService jspService = (JspService)TurbineServices.getInstance().getService( JspService.SERVICE_NAME );

            // this is only necessary if we don't run in a JSP page environment
            // but better be safe than sorry...
            jspService.addDefaultObjects( rundata );
            
	    // save some variables for later use inside of the JSP page
	    // and the action object
	    HttpServletRequest request = rundata.getRequest();
	    request.setAttribute( "data", rundata );
	    request.setAttribute( "portlet", this );
	    request.setAttribute( "template", template );
	    request.setAttribute( "conf", this.getPortletConfig() );
	    request.setAttribute( "skin", this.getPortletConfig().getPortletSkin() );
	    request.setAttribute( "jlink", new PortletTemplateLink( rundata, this ) );
	    buildContext( rundata, request );
	    

	    // retrieve and execute the action object
	    String actionName = getPortletConfig().getInitParameter( "action" );
	    if( actionName != null ) {
		// store the context so that the action can retrieve it
		Log.debug( "MyJSPPortlet found action " + actionName );
		//rundata.getTemplateInfo().setTemplateContext( "VelocityPortletContext", context );
		
		// if there is an action with the same name in modules/actions/portlets exec it
		try {
		    ActionLoader.getInstance().exec( rundata, actionName );
		} catch( Exception e) {
		    System.out.println( "Exception during executing action in MyJSPPortlet: " + e );
		    Log.error( e );
		}
	    }


	    // Retrieve template, because action could have changed it. Then format and locate it.
	    template = (String)request.getAttribute( "template" );
            if( -1 == template.indexOf(".jsp") )  
		template = template + ".jsp";            
            String locatedTemplate = TemplateLocator.locatePortletTemplate( rundata, template );

            // execute JavaServer Page
            jspService.handleRequest( rundata, locatedTemplate );
            
        } catch (Exception e) {
            result = "MyJSPPortlet: Could not include the following JSP Page:  " + template + " : " + e.getMessage();
            Log.error( result, e );
        }
        return new StringElement( result );
    }
}

