package org.seasar.jsf.render.html;

import java.io.IOException;

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

import org.seasar.framework.exception.EmptyRuntimeException;
import org.seasar.jsf.JsfConstants;
import org.seasar.jsf.component.html.HtmlLink;

public class HtmlLinkRenderer 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.LINK_ELEM, component);
		HtmlLink link = (HtmlLink) component;
		String href = link.getHref();
		if (href == null) {
			throw new EmptyRuntimeException("href");
		}
		if (!href.startsWith("/")) {
			href = "/" + href;
		}
		ExternalContext extContext = context.getExternalContext();
		String contextPath = extContext.getRequestContextPath();
		if (!"/".equals(contextPath)) {
			href = contextPath + href;
		}
		writer.writeAttribute(JsfConstants.HREF_ATTR, href, null);
		String rel = link.getRel();
		if (rel != null) {
			writer.writeAttribute(JsfConstants.REL_ATTR, rel, null);
		}
		String type = link.getType();
		if (type != null) {
			writer.writeAttribute(JsfConstants.TYPE_ATTR, type, null);
		}
		String media = link.getMedia();
		if (media != null) {
			writer.writeAttribute(JsfConstants.MEDIA_ATTR, media, null);
		}
		writer.endElement(JsfConstants.LINK_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 {
	}
}