package com.heckmansoft.surjey.controller.action;

import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.heckmansoft.surjey.model.datastore.DatastoreException;
import com.heckmansoft.surjey.model.manager.ResponseManager;
import com.heckmansoft.surjey.model.vo.list.ValueObjectList;
import com.heckmansoft.surjey.model.vo.*;

/**
 * Abstract superclass for all Response actions.
 */
public abstract class ResponseAction extends Action
{
    ResponseManager responseManager;

    Logger log = Logger.getLogger(ResponseAction.class);

    /**
     * Constructor.
     * @param source The source creating this action.
     */
    public ResponseAction(Object source) {
        super(source);
        responseManager = new ResponseManager();
    }

    /**
     * Parse a request for a new survey
     */
    public Response parseRequest(HttpServletRequest request)
    throws Exception {
        // Get the survey id from the request
        String surveyId = (String) request.getParameter("surveyId");

        Response response = responseManager.createResponse();
        response.setSurveyId(surveyId);
        response.setRespondentAddress((String) request.getRemoteAddr());
        response.setResponseAnswers(parseRequestAnswers(request,surveyId));

        return response;
    }

    private ValueObjectList parseRequestAnswers(HttpServletRequest request, String surveyId)
    throws Exception {
        log.debug("parseRequestAnswers(request,"+surveyId+")");

        ValueObjectList answers = new ValueObjectList();

        ValueObjectList sections, questions;
        Section section;
        Question question;
        Iterator questionsIterator;
        Iterator sectionsIterator;
        String qid;

        // Get the survey
        Survey survey = surveyManager.findById(surveyId);
        sections = survey.getSections();

        // Process each section
        sectionsIterator = sections.iterator();
        while (sectionsIterator.hasNext()) {
            section = (Section) sectionsIterator.next();
            questions = section.getQuestions();

            // Process each question
            questionsIterator = questions.iterator();
            while (questionsIterator.hasNext()) {
                question = (Question) questionsIterator.next();
                qid = question.getId();

                ResponseAnswer answer = new ResponseAnswer();
                answer.setQuestionId(qid);

                String ans = new String();
                String[] anss = request.getParameterValues("q" + qid);

                if (anss != null && anss.length > 0) {
                    ans += anss[0];

                    for (int i = 1; i < anss.length; i++) {
                        ans += ", " + anss[i];
                    }
                }

                answer.setAnswer(ans);
                answers.add(answer);
            }
        }
        return answers;
    }
}
