package com.heckmansoft.surjey.view;

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

import com.heckmansoft.surjey.model.vo.Question;

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

    protected String[] answers;
    protected int index;

    /**
     * @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 Question)) {
            throw new JspException("context attribute \""+use+"\" is not a Question.");
        } else {
            // Split answer labels
            answers = ((Question) obj).getAnswerLabels().split(", *");
            index = 0;
            return (handleAnswer() ? EVAL_BODY_INCLUDE : SKIP_BODY);
        }
    }

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

    /**
     * Convenience method for handler.
     * If there is an answer left, store it in the pageContext.
     * @return true if answer was stored, false otherwise.
     */
    private boolean handleAnswer() {
        if (index >= answers.length) return false;

        pageContext.setAttribute(var, answers[index]);
        index++;
        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;
    }
}
