package com.heckmansoft.surjey.view;

import java.util.Iterator;
import java.util.List;

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

import com.heckmansoft.surjey.model.vo.Section;
import com.heckmansoft.surjey.model.vo.Survey;

/**
 * Helper class for rendering a section.
 * This is the Tag Handler class for a Tag Extension as defined
 * in the JSP Specification.
 * @see javax.servlet.jsp.tagext.TagSupport
 */
public class RenderSectionsTagHandler extends TagSupport {
    private String use;
    private String var;
    private Iterator iterator;

    /**
     * @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
     */
    public int doStartTag() throws JspException {
        Object obj = pageContext.findAttribute(use);

        if (obj == null) {
            throw new JspException(use+" not in context.");
        } else if (!(obj instanceof Survey)) {
            throw new JspException("context attribute \""+use+"\" is not a Survey.");
        } else {
            List sections = ((Survey) obj).getSections();
            if (sections == null) { return SKIP_BODY; }
            iterator = sections.iterator();
            return (handleSection() ? EVAL_BODY_INCLUDE : SKIP_BODY);
        }
    }

    /**
     * @see javax.servlet.jsp.tagext.TagSupport#doAfterBody()
     */
    public int doAfterBody() throws JspException {
        return (handleSection() ? EVAL_BODY_AGAIN : SKIP_BODY);
    }

    /**
     * Convenience method for handler.
     * If there is a section left, store it in the pageContext.
     * Get the questions from the section, and store them too.
     * @return true if section was stored, false otherwise.
     */
    private boolean handleSection() {
        if (! iterator.hasNext()) return false;

        pageContext.setAttribute(var, (Section) iterator.next());

        return true;
    }

    /**
     * Get the value of var.
     */
    public String getVar() {
        return var;
    }

    /**
     * Set the value of var.
     */
    public void setVar(String var) {
        this.var = var;
    }

    /**
     * Get the value of use.
     */
    public String getUse() {
        return use;
    }

    /**
     * Set the value of use.
     */
    public void setUse(String use) {
        this.use = use;
    }
}
