/* Head.java

	Purpose:
		
	Description:
		
	History:
		2013/6/27, Dennis

Copyright (C) 2010 Potix Corporation. All Rights Reserved.

*/
package org.zkoss.zss.jsf.ui;

import java.io.IOException;

import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.zkoss.util.logging.Log;
import org.zkoss.zk.ui.Desktop;
import org.zkoss.zk.ui.GenericRichlet;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.sys.DesktopCtrl;
import org.zkoss.zkplus.embed.Renders;

/**
 * Represents a custom JSF component that wraps zk head scripts and css
 * @author Dennis
 *
 */
@FacesComponent(value = "org.zkoss.zss.Head")
public class Head extends UIComponentBase {
	private static final Log log = Log.lookup(Head.class);
	
	public void encodeBegin(FacesContext context) throws IOException {
		
		ServletContext svlctx = (ServletContext)context.getExternalContext().getContext();
		HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
		HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
		ResponseWriter responseWriter = context.getResponseWriter();

		try {
			Renders.render(svlctx, request, response, 
					new GenericRichlet() {
						public void service(Page page) throws Exception {
							//just for output head, remove unnecessary page
							Desktop dt = page.getDesktop();
							((DesktopCtrl)dt).removePage(page);
						}
					}, null, responseWriter);
		} catch (ServletException e) {
			log.debug(e.getMessage());
			throw new IOException(e.getMessage());
		}
		
	}

	
	public String getFamily() {
		return "zk";
	}
}
