package org.seasar.jsf.render.html;

import java.io.IOException;

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

import org.seasar.jsf.JsfConstants;
import org.seasar.jsf.component.html.HtmlBase;
import org.seasar.jsf.util.FacesContextUtil;

public class HtmlBaseRenderer extends Renderer {

	/**
	 * @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;
		}
	}

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

		if (!component.isRendered()) {
			return;
		}
		ResponseWriter writer = context.getResponseWriter();
		writer.startElement(JsfConstants.BASE_ELEM, component);
		HtmlBase base = (HtmlBase) component;
		String href = base.getHref();
		if (href == null) {
			HttpServletRequest request = FacesContextUtil.getRequest(context);
			href = calculateHref(request);
		}
		writer.writeAttribute(JsfConstants.HREF_ATTR, href, null);
		String target = base.getTarget();
		if (target != null) {
			writer.writeAttribute(JsfConstants.TARGET_ATTR, target, null);
		}
		writer.endElement(JsfConstants.BASE_ELEM);
	}

	public String calculateHref(HttpServletRequest request) {
		StringBuffer url = new StringBuffer();
		url.append(request.getScheme());
		url.append("://");
		url.append(request.getServerName());
		url.append(':');
		url.append(request.getServerPort());
		url.append(request.getRequestURI());
		return url.toString();
	}

	/**
	 * @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 {
	}
}