/*
 * WebWork, Web Application Framework
 *
 * Distributable under Apache license.
 * See terms of license at opensource.org
 */
package net.killingar.webwork.view.taglib;

import webwork.util.TextUtil;
import webwork.util.BeanUtil;

import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import java.util.Iterator;

/**
 *  Access the value of a named property. By default (implicitly),
 *  this tag will escape its contents if it does *not* have a body.
 *  If it does have a body, the tag will not escape the contents.
 *  You can explicitly tell the tag to escape or not.
 *  Quoted text that is escaped will have its quotes stripped off.
 *
 * @author Rickard Öberg (rickard@dreambean.com)
 * @author Matt Baldree (matt@smallleap.com)
 * @version $Revision: 1.1 $
 */
public class PrintTag extends webwork.view.taglib.WebWorkTagSupport
{
	// Attributes ----------------------------------------------------
	protected String valueAttr;
	protected Boolean escape;

	// Public --------------------------------------------------------
	public void setValue(String inName)
	{
		valueAttr = inName;
	}

	public void setEscape(boolean inEscape)
	{
		escape = new Boolean(inEscape);
	}

	// BodyTag implementation ----------------------------------------
	public int doStartTag() throws JspException
	{
		Object value = findValue(valueAttr);

		try
		{
			if (value != null)
			{
				if (value instanceof Iterator)
				{
					Iterator enum = (Iterator) value;
					if (enum.hasNext())
						write(enum.next());
				}
				else if (value instanceof char[])
					write(String.valueOf((char[]) value));
				else
					write(value);
			}
			else
				pageContext.getOut().write(""); // Printing out null gives no output
		}
		catch (Exception e)
		{
			throw new JspTagException("Could not show value " + valueAttr + ":" + e);
		}

		return SKIP_BODY;
	}

	private void write(Object output)	throws java.io.IOException
	{
		String s = BeanUtil.toStringValue(output);
		if (escape.booleanValue())
			s = TextUtil.escapeHTML(s);

		pageContext.getOut().write(s);
	}
}