package de.proveo.rts.web.portlet;

import java.io.IOException;

import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.UnavailableException;

/**
 * <a href="MyFacesFaceletsPortlet.java.html"><b><i>View Source</i></b></a>
 * 
 * @author Raymond Auge
 */
public class MyFacesFaceletsPortlet extends org.apache.myfaces.portlet.MyFacesGenericPortlet
{
	private final String PORTLET_MODE_CHANGED = "isPortletModeChanged";
	private final String CURRENT_PORTLET_MODE = "CurrentPortletMode";
	private String _editPage = null;
	private String _helpPage = null;
	private String _viewPage = null;

	public void init() throws UnavailableException, PortletException
	{
		_editPage = (String)this.getInitParameter("EditPage");
		_helpPage = (String)this.getInitParameter("HelpPage");
		_viewPage = (String)this.getInitParameter("ViewPage");
		
		super.init();
	}

	public void render(RenderRequest request, RenderResponse response) 
		throws IOException, PortletException
	{
		PortletSession session = request.getPortletSession();
		PortletMode mode = (PortletMode)session.getAttribute(CURRENT_PORTLET_MODE);

		if (mode == null)
		{
			mode = request.getPortletMode();
		}

		if (mode != request.getPortletMode())
		{
			request.setAttribute(PORTLET_MODE_CHANGED, Boolean.TRUE);
		}
		else
		{
			request.setAttribute(PORTLET_MODE_CHANGED, Boolean.FALSE);
		}

		session.setAttribute(CURRENT_PORTLET_MODE, mode);

		super.render(request, response);
	}

	protected void setDefaultView() throws UnavailableException
	{
		defaultView = getPortletConfig().getInitParameter(DEFAULT_VIEW);
		if (defaultView == null)
		{
			defaultView = _viewPage;
			throw new UnavailableException("Default JSF view is not specified in portlet.xml");
		}
	}

	protected void doEdit(RenderRequest request, RenderResponse response) 
		throws IOException, PortletException
	{
		Boolean isPortletModeChanged = (Boolean)request.getAttribute(PORTLET_MODE_CHANGED);
		Boolean myfacesRequest = request.getParameterMap().containsKey("org.apache.myfaces.portlet.MyFacesGenericPortlet.VIEW_ID");
		String portletName = getPortletConfig().getResourceBundle(request.getLocale()).getString("javax.portlet.title");
		request.getPortletSession().setAttribute("portletName", portletName);
		if (isPortletModeChanged.booleanValue() && !myfacesRequest)
		{
			setPortletRequestFlag(request);
			nonFacesRequest(request, response, _editPage);
			return;
		}

		facesRender(request, response);
	}

	protected void doHelp(RenderRequest request, RenderResponse response) 
		throws IOException, PortletException
	{
		Boolean isPortletModeChanged = (Boolean)request.getAttribute(PORTLET_MODE_CHANGED);
		if (isPortletModeChanged.booleanValue())
		{
			setPortletRequestFlag(request);
			nonFacesRequest(request, response, _helpPage);
			return;
		}

		facesRender(request, response);
	}
}
