package it.mice.voila.runtime.springmvc.taglibs;

import java.util.UUID;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.tags.form.AbstractHtmlElementTag;
import org.springframework.web.servlet.tags.form.TagWriter;

public class HelpTag extends AbstractHtmlElementTag {
	private static final String DOJO = "dojo";
	private static final String TITLE = "title";
	
	private String type = DOJO;
	private String titleKey = null;
	
    public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	/**
	 * @return the titleKey
	 */
	public String getTitleKey() {
		return titleKey;
	}

	/**
	 * @param titleKey the titleKey to set
	 */
	public void setTitleKey(String titleKey) {
		this.titleKey = titleKey;
	}

	/**
	 * serial version UID
	 */
	private static final long serialVersionUID = 1365950626443575870L;
	
	@Override
	protected int writeTagContent(TagWriter tagWriter) throws JspException {
		if (StringUtils.isEmpty(getCssClass())) {
			if (TagUtils.isBootstrapTheme()) {
				setCssClass("help fa fa-question-circle");
			} else {
				setCssClass("help");
			}
		}
		if (!StringUtils.isEmpty(getTitleKey())) {
			setTitle(TagUtils.getMessage(getRequestContext(), getTitleKey(), getTitle()));
		}
		if (StringUtils.isEmpty(getId())) {
			if (!StringUtils.isEmpty(getTitleKey())) {
				setId(getTitleKey());
			} else {
				setId(UUID.randomUUID().toString());
			}
		}
		String htmlTitle = it.mice.voila.runtime.util.StringUtils.stripCrLf(getTitle());
		setTitle(it.mice.voila.runtime.util.StringUtils.stripHtml(getTitle()));
		
		tagWriter.startTag("span");
		writeDefaultAttributes(tagWriter);
		tagWriter.endTag(true);

		if (DOJO.equals(getType())) {
			tagWriter.startTag("script");
			tagWriter.writeAttribute("type", "text/javascript");
			tagWriter.appendValue("dojo.addOnLoad(function() {");
			tagWriter.appendValue("new dijit.Tooltip({connectId: [\"" + getId() + "\"], label: \"" + htmlTitle + "\"});");
			tagWriter.appendValue("document.getElementById(\"" + getId() + "\").title = \"\";");
			tagWriter.appendValue("});");
			tagWriter.endTag();
		}
		return SKIP_BODY;
	}
	
	@Override
	public void doFinally() {
		setType(DOJO);
		setTitleKey(null);
		setCssClass(null);
		setCssStyle(null);
		setTitle(null);
		setId(null);
		super.doFinally();
	}

}
