package com.heckmansoft.surjey.view;

import java.util.Iterator;

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

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

/**
 * Helper class for rendering a question.
 * This is the Tag Handler class for a Tag Extension as defined
 * in the JSP Specification.
 * @see javax.servlet.jsp.tagext.TagSupport
 */
public class RenderQuestionsTagHandler 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 Section)) {
            throw new JspException("context attribute \""+use+"\" is not a Section.");
        } else {
            iterator = ((Section) obj).getQuestions().iterator();
            return (handleQuestion() ? EVAL_BODY_INCLUDE : SKIP_BODY);
        }
    }

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

    /**
     * Convenience method for handler.
     * If there is an question left, store it in the pageContext.
     * Get the answer labels for the question, and store them too.
     * If the question type is "Textbox", split the size into rows and
     * columns, and store these separately as well.
     * @return true if question was stored, false otherwise.
     */
    private boolean handleQuestion() {
        if (! iterator.hasNext()) return false;

        Question question = (Question) iterator.next();

        pageContext.setAttribute(var, question);

        if (question.getQuestionType().getName().equals("Textbox")) {
            String[] dims = question.getDisplaySize().split(", *");
            String cols = (dims.length > 0 ? dims[0] : "40");
            String rows = (dims.length > 1 ? dims[1] : "10");
            pageContext.setAttribute("qcols", cols);
            pageContext.setAttribute("qrows", rows);
        }

        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;
    }
}
