package org.ajax4jsf.portlet.application;

import java.io.IOException;
import java.io.Writer;

import javax.faces.FacesException;
import javax.faces.application.ViewHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.RenderKit;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.sun.facelets.FaceletViewHandler;

/**
 * ViewHandler implementation for Facelets used in Portlets
 * 
 */
public class FaceletPortletViewHandler extends FaceletViewHandler {
    private static final Writer nullWriter = new Writer() {
	public void close() throws IOException {
	    // Do nothing
	}

	public void flush() throws IOException {
	    // Do nothing
	}

	public void write(char[] cbuf, int off, int len) throws IOException {
	    // Do nothing
	}
    };

    public FaceletPortletViewHandler(ViewHandler parent) {
	super(parent);
    }

    protected ResponseWriter createResponseWriter(FacesContext context)
	    throws IOException, FacesException {
	ResponseWriter writer;
	ExternalContext extContext = context.getExternalContext();
	if (extContext.getResponse() instanceof RenderResponse) {
	    RenderKit renderKit = context.getRenderKit();
	    RenderRequest request = (RenderRequest) extContext.getRequest();
	    RenderResponse response = (RenderResponse) extContext.getResponse();
	    String contenttype = request.getResponseContentType();
	    if (contenttype == null) {
	    	contenttype = "text/html";
	    }
	    String encoding = response.getCharacterEncoding();
	    if (encoding == null) {
	    	encoding = "UTF-8";
	    }
	    writer = renderKit.createResponseWriter(nullWriter, contenttype,
		    encoding);
	    contenttype = writer.getContentType();
	    // apply them to the response
	    response.setContentType(contenttype);
	    // Now, clone with the real writer
	    writer = writer.cloneWithWriter(response.getWriter());
	} else {
	    writer = super.createResponseWriter(context);
	}
	return writer;
    }
}