package org.seasar.jsf.render.html;

import java.io.IOException;

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

import org.seasar.jsf.JsfConstants;
import org.seasar.jsf.util.RenderUtil;
import org.seasar.jsf.util.ValueHolderUtil;

public class HtmlSpanRenderer extends HtmlTagRenderer {

	/**
	 * @see javax.faces.render.Renderer#encodeBegin(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
	 */
	public void encodeBegin(FacesContext facesContext, UIComponent component)
			throws IOException {

		if (!component.isRendered()) {
			return;
		}
		ResponseWriter writer = facesContext.getResponseWriter();
		writer.startElement(JsfConstants.SPAN_ELEM, component);
		renderPathThroughAttributes(writer, component);
		if (component instanceof ValueHolder) {
			String text = ValueHolderUtil.getStringValue(facesContext, component);
			if (text != null) {
				writer.writeText(text, "value");
			}
		}
	}

	/**
	 * @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
	 */
	public void encodeEnd(FacesContext facesContext, UIComponent component)
			throws IOException {

		if (!component.isRendered()) {
			return;
		}
		ResponseWriter writer = facesContext.getResponseWriter();
		writer.endElement(JsfConstants.SPAN_ELEM);
	}
	
	/**
	 * @see javax.faces.render.Renderer#getRendersChildren()
	 */
	public boolean getRendersChildren() {
		return true;
	}
	
	/**
	 * @see javax.faces.render.Renderer#encodeChildren(javax.faces.context.FacesContext, javax.faces.component.UIComponent)
	 */
	public void encodeChildren(FacesContext context, UIComponent component)
			throws IOException {

		if (!component.isRendered()) {
			return;
		}
		if (component instanceof ValueHolder) {
			ValueHolder vh = (ValueHolder) component;
			if (vh.getValue() != null) {
				return;
			}
		}
		RenderUtil.encodeChildren(context, component);
	}
}