/**
 * 
 */
package org.ajax4jsf.portlet.application;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.portlet.PortletURL;
import javax.portlet.RenderResponse;

import org.ajax4jsf.application.AjaxViewHandler;
import org.ajax4jsf.context.AjaxContext;
import org.ajax4jsf.portlet.context.AbstractExternalContext;

/**
 * @author asmirnov
 *
 */
public class PortletViewHandler extends AjaxViewHandler {
    /**
     * @param parent
     */
    public PortletViewHandler(ViewHandler parent) {
	super(parent);
    }
    
    
    public void initView(FacesContext context) throws FacesException {
    	super.initView(context);
    }
    
    public UIViewRoot createView(FacesContext facesContext, String viewId) {
        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(facesContext);
        boolean ajaxRequest = ajaxContext.isAjaxRequest(facesContext);
        UIViewRoot root = super.createView(facesContext, viewId);
        if(ajaxRequest && null != ajaxContext.getViewIdHolder()){
            // Store new viewId for a portlet.
        }
        return root;
    }

    public void renderView(FacesContext context, UIViewRoot root) throws IOException, FacesException {
        super.renderView(context, root);
        // Save view to use in portlet rendering phases
//	PortletViewState state = new PortletViewState();
//	state.save(context);
//	context.getExternalContext().getSessionMap().put(
//		PortletViewState.SAVED_VIEW_ATTRIBUTE, state);

    }
    
    public String getActionURL(FacesContext context, String url) {
        ExternalContext externalContext = context.getExternalContext();
        String portalActionURL = (String) externalContext.getRequestParameterMap().get(AbstractExternalContext.ACTION__PARAMETER);
	Object response = externalContext.getResponse();
	if (response instanceof RenderResponse) {
	    RenderResponse renderResponse = (RenderResponse) response;
	    PortletURL portletURL = renderResponse.createActionURL();
//	    portletURL.setParameter(AbstractExternalContext.VIEW_ID_PARAMETER, context.getViewRoot().getViewId());
//	    portletURL.setParameter(AbstractExternalContext.NAMESPACE_PARAMETER, renderResponse.getNamespace());
	    return portletURL.toString();
	} else if(null!=portalActionURL){
	    return portalActionURL;
	} else {
	    return super.getActionURL(context, url);
	}
    }
    
    protected synchronized void fillChain(FacesContext context) {
        // Do nothing - chain must be filled in AjaxViewHandler
    }
}
