package org.seasar.jsf.render.html;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

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

import org.seasar.jsf.JsfConstants;
import org.seasar.jsf.component.UIElement;
import org.seasar.jsf.util.BindingUtil;
import org.seasar.jsf.util.RenderUtil;

public class HtmlElementRenderer extends Renderer {

	public void encodeBegin(FacesContext facesContext, UIComponent component)
			throws IOException {

		if (!component.isRendered()) {
			return;
		}
		ResponseWriter writer = facesContext.getResponseWriter();
		if (!(component instanceof UIElement)) {
			throw new IllegalArgumentException("not UIElementNode");
		}
		UIElement elem = (UIElement) component;
		String tagName = elem.getTagName();
		writer.startElement(tagName, component);
		renderAttributes(writer, elem);
	}

	public void encodeEnd(FacesContext facesContext, UIComponent component)
			throws IOException {

		if (!component.isRendered()) {
			return;
		}
		ResponseWriter writer = facesContext.getResponseWriter();
        UIElement elem = (UIElement) component;
		writer.endElement(elem.getTagName());
        String afterContents = elem.getAfterContents();
        if (afterContents != null) {
            writer.write(afterContents);
        }
	}

	/**
	 * @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;
		}
		RenderUtil.encodeChildren(context, component);
	}

	protected void renderAttributes(ResponseWriter writer, UIElement component)
			throws IOException {

		if (component.isIdSet()) {
			String id = component.getId();
			RenderUtil.renderAttribute(writer, JsfConstants.ID_ATTR, id, JsfConstants.ID_ATTR);
		}
		Map attrs = component.getAttributes();
		for (Iterator i = attrs.keySet().iterator(); i.hasNext();) {
			String attrName = (String) i.next();
			if (attrName.indexOf('.') > 0) {
				continue;
			}
			Object value = component.getAttributes().get(attrName);
			RenderUtil.renderAttribute(writer, attrName, value, attrName);
		}
		String[] bindingPropertyNames = component.getBindingPropertyNames();
		for (int i = 0; i < bindingPropertyNames.length; ++i) {
			String name = bindingPropertyNames[i];
			Object value = BindingUtil.getBindingValue(component, name);
			RenderUtil.renderAttribute(writer, name, value, name);
		}
	}
}