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

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;

import org.apache.taglibs.standard.tag.rt.core.IfTag;

import it.mice.voila.runtime.springmvc.bean.PageStatus;
import it.mice.voila.runtime.springmvc.form.JfFormBean;

public class PageStatusTag extends IfTag {
	/**
	 * serial
	 */
	private static final long serialVersionUID = 3407922243756477174L;

	private static final String DEFAULT_PAGE_STATUS = "READ";

	private static final String JF_OLD_PAGE_STATUS = "jf.old.pageStatus";
	
	private String pageStatus = DEFAULT_PAGE_STATUS;
	
	/**
	 * @return the pageStatus
	 */
	public String getPageStatus() {
		return pageStatus.toUpperCase();
	}

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

	/**
     * Includes its body if condition() evaluates to true.
     */
    public int doStartTag() throws JspException {

        // execute our condition() method once per invocation
        boolean result = condition();

        // handle conditional behavior
        if (result) {
    		JfFormBean form = TagUtils.getFormBean(pageContext);
            if (form != null) {
                pageContext.setAttribute(JF_OLD_PAGE_STATUS, form.getPageStatus(), PageContext.PAGE_SCOPE);
            	form.setPageStatus(PageStatus.forName(getPageStatus()));
            } else {
				throw new JspException("PageStatusTag can only be used with embedded JfFormBean type.");
            }
        }
        return EVAL_BODY_INCLUDE;
    }

    
    /* (non-Javadoc)
	 * @see javax.servlet.jsp.tagext.TagSupport#doEndTag()
	 */
	@Override
	public int doEndTag() throws JspException {
		PageStatus pageStatusToRestore = (PageStatus) pageContext.getAttribute(
				JF_OLD_PAGE_STATUS, PageContext.PAGE_SCOPE);
		JfFormBean form = TagUtils.getFormBean(pageContext);
		if (form != null && pageStatusToRestore != null) {
			form.setPageStatus(pageStatusToRestore);
		}
		return super.doEndTag();
	}

	/**
     * Releases any resources this ConditionalTagSupport may have (or inherit).
     */
    public void release() {
        super.release();
        setPageStatus(DEFAULT_PAGE_STATUS);
    }

}
