/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

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

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