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

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import org.ajax4jsf.context.AjaxContext;
import org.ajax4jsf.portlet.context.AbstractExternalContext;
import org.ajax4jsf.renderkit.AjaxContainerRenderer;
import org.ajax4jsf.renderkit.AjaxRendererUtils;
import org.ajax4jsf.renderkit.AjaxViewRootRenderer;
import org.ajax4jsf.renderkit.RendererUtils.HTML;

/**
 * @author asmirnov
 *
 */
public class PortletAjaxViewRootRenderer extends AjaxViewRootRenderer {
    protected void doEncodeBegin(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException {
        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
        Object namespace = context.getExternalContext().getRequestParameterMap().get(AbstractExternalContext.NAMESPACE_PARAMETER);
        Object ajaxRequestParameter = context.getExternalContext().getRequestParameterMap().get(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
        if(!ajaxContext.isAjaxRequest() && null !=namespace && null != ajaxRequestParameter){
            // Navigation case, encode portlet window marker
            writer.startElement(HTML.DIV_ELEM, component);
            writer.writeAttribute(HTML.id_ATTRIBUTE, namespace, HTML.id_ATTRIBUTE);
        }
        super.doEncodeBegin(writer, context, component);
    }
    
    protected void doEncodeEnd(ResponseWriter writer, FacesContext context, UIComponent component) throws IOException {
        super.doEncodeEnd(writer, context, component);
        AjaxContext ajaxContext = AjaxContext.getCurrentInstance(context);
        Object namespace = context.getExternalContext().getRequestParameterMap().get(AbstractExternalContext.NAMESPACE_PARAMETER);
        Object ajaxRequestParameter = context.getExternalContext().getRequestParameterMap().get(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
        if(!ajaxContext.isAjaxRequest() && null !=namespace && null != ajaxRequestParameter){
            // Navigation case, encode portlet window marker
            writer.endElement(HTML.DIV_ELEM);
            ajaxContext.setAjaxRequest(true);
            ajaxContext.addRenderedArea(namespace.toString());
            AjaxRendererUtils.encodeAreas(context, component);            
        }
    }
}
