/*
 * This file is part of Nuts Framework.
 * Copyright (C) 2009 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.struts2.components;

import java.io.IOException;
import java.io.Writer;
import java.text.ChoiceFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import nuts.core.lang.StringUtils;
import nuts.exts.xwork2.util.ContextUtils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.components.ContextBean;
import org.apache.struts2.views.annotations.StrutsTag;
import org.apache.struts2.views.annotations.StrutsTagAttribute;

import com.opensymphony.xwork2.TextProvider;
import com.opensymphony.xwork2.util.ValueStack;


/**
 * <!-- START SNIPPET: javadoc -->
 *
 * Format Boolean object.
 *
 * <p/>
 *
 * Configurable attributes are :-
 * <ul>
 *    <li>name</li>
 *    <li>value</li>
 *    <li>format</li>
 * </ul>
 *
 * <p/>
 *
 * <!-- END SNIPPET: javadoc -->
 *
 * <p/> <b>Examples</b>
 * <pre>
 *  <!-- START SNIPPET: example -->
 *  &lt;r:boolean name="person.birthday" /&gt;
 *  &lt;r:boolean value=true /&gt;
 *  <!-- END SNIPPET: example -->
 * </pre>
 *
 * <code>Boolean</code>
 *
 */
@StrutsTag(
		name="Boolean", 
		tldBodyContent="empty", 
		tldTagClass="nuts.exts.struts2.views.jsp.BooleanTag", 
		description="Render a formatted boolean.")
public class CBoolean extends ContextBean {

	/**
	 * log
	 */
	private static final Log log = LogFactory.getLog(CBoolean.class);

	/**
	 * format cache
	 */
	private static Map<String, ChoiceFormat> formatCache = new ConcurrentHashMap<String, ChoiceFormat>();
	
	/**
	 * BOOLEAN_FORMAT_DEFAULT = "boolean-format";
	 */
	public static final String BOOLEAN_FORMAT_DEFAULT = "boolean-format";

	/**
	 * BOOLEAN_FORMAT_PREFIX = "boolean-format-";
	 */
	public static final String BOOLEAN_FORMAT_PREFIX = "boolean-format-";

	private String name;

	private Object value;

	private String format;

	/**
	 * Constructor
	 * 
	 * @param stack value stack
	 */
	public CBoolean(ValueStack stack) {
		super(stack);
	}

	/**
	 * @see org.apache.struts2.components.Component#end(java.io.Writer, java.lang.String)
	 */
	public boolean end(Writer writer, String body) {
		Boolean b = null;

		if (value != null) {
			if (value instanceof Boolean) {
				b = (Boolean)value; 
			}
			else {
				getStack().push(value);
				try {
					b = (Boolean)findValue("top", Boolean.class);
				}
				catch (Exception e) {
					log.warn("Could not convert value '" + value
						+ "' to a Boolean instance");
				}
				getStack().pop();
			}
		}
		else if (name != null) {
			// find the name on the valueStack, and cast it to a boolean
			try {
				b = (Boolean)findValue(name, Boolean.class);
			}
			catch (Exception e) {
				log.warn("Could not convert object with key '" + name
						+ "' to a Boolean instance");
			}
		}

		if (b != null) {
			ValueStack stack = getStack();
			TextProvider tp = ContextUtils.findTextProviderInStack(stack);
			String pattern = null;

			if (StringUtils.isNotEmpty(format)) {
				pattern = tp.getText(BOOLEAN_FORMAT_PREFIX + format, (String) null);
				if (pattern == null) {
					pattern = format;
				}
			}
			else {
				pattern = tp.getText(BOOLEAN_FORMAT_DEFAULT, (String) null);
			}

			String msg = null;
			if (pattern != null) {
				ChoiceFormat cf = formatCache.get(pattern);
				if (cf != null) {
					try {
						msg = cf.format(b ? 1 : 0);
					}
					catch (Exception e) {
						log.warn("The format '" + pattern + "' is not a valid ChoiceFormat expression.", e);
					}
				}
				else {
					try {
						cf = new ChoiceFormat(pattern);
						msg = cf.format(b ? 1 : 0);
						formatCache.put(pattern, cf);
					}
					catch (Exception e) {
						getStack().push(b);
						try {
							msg = findValue(pattern).toString();
						}
						catch (Exception e2) {
							log.warn("The format '" + pattern + "' is not a valid OGNL/ChoiceFormat expression.", e2);
						}
						getStack().pop();
					}
				}
			}

			if (msg == null) {
				msg = b.toString();
			}

			try {
				if (getVar() == null) {
					writer.write(msg);
				}
				else {
					putInContext(msg);
				}
			}
			catch (IOException e) {
				log.warn("Could not write out Boolean tag", e);
			}
		}
		return super.end(writer, "");
	}

	/**
	 * @param name the name to set
	 */
	@StrutsTagAttribute(description="The boolean value name to format", required=false)
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @param value the value to set
	 */
	@StrutsTagAttribute(description="The boolean value to format", required=false)
	public void setValue(Object value) {
		this.value = value;
	}

	/**
	 * @param format the format to set
	 */
	@StrutsTagAttribute(description="The number format to use", rtexprvalue=false)
	public void setFormat(String format) {
		this.format = format;
	}
}
