/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  All rights reserved.
  
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

====================================================================== */

package org.bodington.assessment;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.bodington.server.BuildingServerException;
import org.bodington.servlet.Request;

/**
 * Class for rendering questionnaires in the <em>edit</em> state. This class
 * is used to render the questionnaire to the author for the purposes of
 * editing. The view that gets rendered enables CRUD type functionality
 * pertaining to questions, i.e. adding, editing and deleting.
 * @author Alexis O'Connor
 */
class EditQuestionnaireRenderer extends AbstractQuestionnaireRenderer
    {
    public void paperToHTML( Request request, PrintWriter out,
        QuestionnaireSession session ) throws IOException,
        BuildingServerException
        {
        List questions_in_order;
        Questionnaire questionnaire = null;
        QuestionnaireQuestion question;

        questionnaire = session.getQuestionnaire();
        questions_in_order = session.getQuestionnaireQuestionsInOrder();
        Iterator ordinals 
            = ordinalList(questionnaire, questions_in_order).iterator();

        // Blank questionnaire?
        if ( questions_in_order.size() == 0 )
            {
            out.println( "<P>There are currently no questions in this "
                + "questionnaire.</P>" );
            out.println( "<p>" ); 
            out.println( "<div style=\"padding-left: 30px\">" ); 
            renderAddQuestionButton( out, ordinals.next() );
            out.println( "</div>" );
            out.println( "</p>" );
            return;
            }
        
        // Button to prepend new question:
        out.println( "<p>" ); 
        out.println( "<div style=\"padding-left: 30px\">" ); 
        renderAddQuestionButton( out, ordinals.next() );
        out.println( "</div>" );
        out.println( "</p>" );
        
        for ( int i = 0; i < questions_in_order.size(); i++ )
            {
            question = (QuestionnaireQuestion)questions_in_order.get( i );

            String identifier = "Q" + question.getQuestionnaireQuestionId();
            out.println( "<P></P><TABLE BORDER id=" + identifier
                + "><TR><TD COLSPAN=2><h4>Question " + (i + 1) + "&nbsp;"
                + "<span style=\"font-size: smaller; font-style: italic\">"
                + "("+ question.getOrdinal() + ")"
                + "</span></h4></TD>" );
            out.print( "<TD ALIGN=CENTER><FORM METHOD=POST ACTION=\"" );
            out.print( request.getContextPath() );
            out.print( request.getServletPath() );
            out.print( questionnaire.getFullName() );
            out.print( question.getQuestionnaireQuestionId()
                + "/bs_template_qeditq.html\">" );
            out.println( "<INPUT TYPE=SUBMIT VALUE=\"Edit This Question\">"
                + "</FORM></TD></TR>" );

            questionToHTML( question, null, out );

            out.println( "</TABLE>" );
            
            // Button to insert / append new question:
            out.println( "<p>" ); 
            out.println( "<div style=\"padding-left: 30px\">" ); 
            renderAddQuestionButton( out, ordinals.next() );
            out.println( "</div>" );
            out.println( "</p>" );
            }
        }

    public void questionToHTML( QuestionnaireQuestion question,
        QuestionnaireResponse response, PrintWriter out ) throws IOException,
        BuildingServerException
        {
        out.println( "<TR><TD COLSPAN=3>" );
        out.println( question.getIntroduction() );
        out.println( "</TD></TR>" );

        int[] indices = question.getValidStatementIndices();
        for ( int i = 0; i < indices.length; i++ )
            {
            char letter = (char)('A' + i);
            out.println( "<TR><TD VALIGN=TOP WIDTH=20><B>" );
            out.println( letter );
            out.println( "</B></TD>" );
            out.println( "<TD VALIGN=TOP WIDTH=1000>" );
            out.println( question.getStatement( indices[i] ) );
            out.println( "</TD></TR>" );
            }

        // Indicate whether the question allows for a comment:
        if ( question.isCanComment() )
            {
            out.println( "<TR><TD COLSPAN=3 ALIGN=CENTER "
                + "style=\"font-size: smaller; font-style: italic\">"
                + "~ This question allows for a free text comment ~"
                + "</TD></TR>" );
            }
        }
    
    private void renderAddQuestionButton( PrintWriter out, Object ordinal )
        {
        out.println("<form method=\"post\" action=\"bs_template_qnewq.html\">"
            + "<input type=\"hidden\" name=\"ordinal\" value=\"" + ordinal + "\">"
            + "<input type=\"submit\" value=\"Insert New Question Here\">"
            + "</form>");
        }
    
    /*
     * NOTES: creates a list of ordinals (Integer) from question list:
     * - this is (obviously) highly coupled to the code that renders it. The
     * key points are that the ordinals are split into prepender, betwixt &
     * appender. If there are no questions, only the prepender exists.
     */
    private List ordinalList( Questionnaire q, List questions )
        {
        List ordinals = new Vector();

        // 1st / Prepender ordinal:
        ordinals.add( new Integer( q.getPreviousOrdinal() ) );

        // Betwixt ordinals:
        for ( int i = 0; i < questions.size() - 1; i++ )
            {
            QuestionnaireQuestion thisQq 
                = (QuestionnaireQuestion)questions.get( i );
            QuestionnaireQuestion nextQq 
                = (QuestionnaireQuestion)questions.get( i + 1 );
            ordinals.add( new Integer( thisQq.getOrdinal() +
                (int)(0.5 * (nextQq.getOrdinal() - thisQq.getOrdinal())) ) );
            }

        // Last / appender ordinal:
        if ( !questions.isEmpty() )
            ordinals.add( new Integer( q.getNextOrdinal() ) );

        return ordinals;
        }
    }
