/**
 * Licensed under the MICE s.r.l.
 * End User License Agreement
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.micegroup.it/voila/license.html
 */
package it.mice.voila.runtime.springmvc.taglibs;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.util.StringUtils;

public class PopupReturnTag extends BodyTagSupport implements Cloneable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8037263685509421774L;

	private String property;
	private String name;
	private String paramName;

	// --------------------------------------------------------- Tag API methods

	public int doEndTag() throws JspException {
		Object parent = this.getParent();

		boolean foundChooseTag = false;

		while (!foundChooseTag) {
			if (parent == null) {
				throw new JspException(
						"Can not use column tag outside of a ChooseTag.");
			}

			if (!(parent instanceof PopupTag)) {
				if (parent instanceof TagSupport)
					parent = ((TagSupport) parent).getParent();
				else
					throw new JspException(
							"Can not use column tag outside of a ChooseTag.");
			} else
				foundChooseTag = true;
		}

		// Need to clone the ColumnTag before passing it to the TableTag as
		// the ColumnTags can be reused by some containers, and since we are
		// using the ColumnTags as basically containers of data, we need to
		// save the original values, and not the values that are being changed
		// as the tag is being reused...

		PopupReturnTag copy = this;
		try {
			copy = (PopupReturnTag) this.clone();
		} catch (CloneNotSupportedException e) {
		} // shouldn't happen...

		((PopupTag) parent).addRetValue(copy);

		return super.doEndTag();
	}

	/**
	 * Returns the name.
	 * 
	 * @return String
	 */
	public String getName() {
		return name;
	}

	/**
	 * Returns the property.
	 * 
	 * @return String
	 */
	public String getProperty() {
		return property;
	}

	/**
	 * Returns the property.
	 * 
	 * @return String
	 */
	public String getPropertyId() {
		return StringUtils.deleteAny(getProperty(), "[]");
	}

	/**
	 * Sets the name.
	 * 
	 * @param name
	 *            The name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * Sets the property.
	 * 
	 * @param property
	 *            The property to set
	 */
	public void setProperty(String property) {
		this.property = property;
	}

	/**
	 * Returns the paramName.
	 * 
	 * @return String
	 */
	public String getParamName() {

		if (paramName == null || paramName.trim().length() == 0)
			return getProperty();

		return paramName;
	}

	/**
	 * Sets the paramName.
	 * 
	 * @param paramName
	 *            The paramName to set
	 */
	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

}
