/* ======================================================================
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 org.apache.log4j.Logger;



import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Hashtable;
import java.sql.Timestamp;
import java.io.*;

import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.ParserConfigurationException;  


import org.bodington.assessment.ims.QuestionnaireImsQtiHandler;
import org.bodington.database.PrimaryKey;
import org.bodington.logging.LoggingUtils;
import org.bodington.server.*;
import org.bodington.text.BigString;
import org.bodington.server.realm.User;
import org.bodington.server.resources.Resource;


/**
 * Concrete implementation of a questionnaire session.
 * @see QuestionnaireQuestion
 * @author Jon Maber
 * @author Alexis O'Connor
 */
public class QuestionnaireSessionImpl
	extends org.bodington.server.SingleResourceSession 
	implements QuestionnaireSession 
	{
    private static Logger log = Logger.getLogger(QuestionnaireSessionImpl.class);
    private Questionnaire questionnaire;
	
	public QuestionnaireSessionImpl()
		throws RemoteException, BuildingServerException
		{
		super();
		}
	

	public Questionnaire getQuestionnaire()
		throws RemoteException, BuildingServerException
		{
        return questionnaire;
		}
		
	
	public List getQuestionnaireQuestionIds() 
        throws RemoteException, BuildingServerException
        {
        Vector list = new Vector();
        Iterator iterator = questionnaire.getQuestions().iterator();
        while ( iterator.hasNext() )
            {
            QuestionnaireQuestion question 
                = (QuestionnaireQuestion) iterator.next();
            list.addElement( question.getQuestionnaireQuestionId() );
            }

        return list;
        }
	
	public Map getQuestionnaireQuestions()
		throws RemoteException, BuildingServerException
		{
		Hashtable table = new Hashtable();
        Iterator iterator = questionnaire.getQuestions().iterator();
		while ( iterator.hasNext() )
			{
            QuestionnaireQuestion question 
                = (QuestionnaireQuestion)iterator.next();
			table.put( question.getQuestionnaireQuestionId(), question );
			}
		
		return table;
		}
	
	public List getQuestionnaireQuestionsInOrder()
		throws RemoteException, BuildingServerException
		{
        return questionnaire.getQuestions();
		}
	
	public Vector getQuestionnaireResults()
		throws RemoteException, BuildingServerException
		{
		Vector list = new Vector();
		
		QuestionnaireResult result;
        // TODO : looks wrong, but see QuestionnaireResult.getResourceId().
		Enumeration enumeration 
            = QuestionnaireResult.findQuestionnaireResults( 
                "resource_id = " + getResource().getResourceId() );
		while ( enumeration.hasMoreElements() )
			{
			result = (QuestionnaireResult)enumeration.nextElement();
			list.addElement( result ); 
			}
		
		return list;
		}
	
	public QuestionnaireQuestion createQuestion()
		throws RemoteException, BuildingServerException
		{
		return questionnaire.createQuestion();
		}
	
	public void removeQuestion( PrimaryKey id )
		throws RemoteException, BuildingServerException
		{
        questionnaire.removeQuestion( id );
		}
	
	public void changeQuestion( PrimaryKey id, QuestionnaireQuestion model )
		throws RemoteException, BuildingServerException
		{
        questionnaire.changeQuestion( id, model);
		}
	
	public void changeQuestionText( PrimaryKey qid, PrimaryKey tid, String new_text )
		throws RemoteException, BuildingServerException
		{
        questionnaire.changeQuestionText( qid, tid, new_text );
		}
	

	public PrimaryKey record( PrimaryKey[] q_question_ids, int[] items, String[] comments )
		throws RemoteException, BuildingServerException
		{
		User user = (User)BuildingContext.getContext().getUser();
		Map q_questions = this.getQuestionnaireQuestions();
		QuestionnaireResponse q_response;
		QuestionnaireQuestion q_question;
		QuestionnaireResult q_result = getQuestionnaireResult( user.getUserId() );
		if ( !q_result.isRecorded() )
			{
			q_result = new QuestionnaireResult();
			q_result.setQuestionnaireId( getResource().getResourceId() );
			q_result.setUserId( user.getUserId() );
			q_result.setWhenStarted( new Timestamp( System.currentTimeMillis() ) );
			q_result.setWhenSaved( new Timestamp( System.currentTimeMillis() ) );
			q_result.save();
			}
		Map responses = q_result.getQuestionnaireResponses();
		q_result.setWhenSaved( new Timestamp( System.currentTimeMillis() ) );
		q_result.save();
		
		for ( int i=0; i< q_question_ids.length; i++ )
			{
			q_question = (QuestionnaireQuestion)q_questions.get( q_question_ids[i] );
			if ( q_question == null )
				throw new BuildingServerException( "Unable to find question data." );
			q_response = (QuestionnaireResponse)responses.get( q_question_ids[i] );
			if ( !q_response.isRecorded() )
				{
				q_response = new QuestionnaireResponse();
				q_response.setQuestionnaireResultId( q_result.getQuestionnaireResultId() );
				q_response.setQuestionnaireQuestionId( q_question_ids[i] );
				q_response.save();
				}
			if ( (items[i]+1) > q_question.getStatementCount() )
				items[i]=100;
			if ( items[i]<0 )
				items[i]=100;
				
			q_response.setItem( (byte)items[i] );
			q_response.setComment( comments[i] );
			q_response.save();
			}

		return q_result.getQuestionnaireResultId();
		}
	
	public QuestionnaireResult getQuestionnaireResult()
		throws RemoteException, BuildingServerException
		{
		User user = (User)BuildingContext.getContext().getUser();
		return getQuestionnaireResult( user.getUserId() );
		}
		
	public QuestionnaireResult getQuestionnaireResult( PrimaryKey uid )
		throws RemoteException, BuildingServerException
		{
        // TODO : looks wrong, but see QuestionnaireResult.getResourceId().
		QuestionnaireResult entry = 
			QuestionnaireResult.findQuestionnaireResult( 
				"resource_id = " + getResource().getResourceId() 
                + " AND user_id = " + uid );
		
		return entry;
		}
		
	public Vector getResultsOfUser()
		throws RemoteException, BuildingServerException
		{
		Vector list = new Vector();
        // TODO : looks wrong, but see QuestionnaireResult.getResourceId().
		Enumeration enumeration = QuestionnaireResult.findQuestionnaireResults( 
					"resource_id = " + this.getResource().getResourceId() + " AND user_id = " + user_id,
					"when_done" );
			
		while ( enumeration.hasMoreElements() )
			list.addElement( enumeration.nextElement() );

		return list;
		}

	public List analyse( String where_clause, QuestionnaireAnalysis analysis )
		throws RemoteException, BuildingServerException
		{
		Vector list = new Vector();
		Enumeration enumeration;
		QuestionnaireResult q_result;
		QuestionnaireResponse q_response;
		QuestionnaireQuestion q_question;
		Map responses;
		List questions=null;
		
		if ( where_clause == null )
            // TODO : looks wrong, but see QuestionnaireResult.getResourceId().
			enumeration = QuestionnaireResult.findQuestionnaireResults( "resource_id = " + getResource().getResourceId() );
		else
			enumeration = QuestionnaireResult.findQuestionnaireResults( where_clause );

		if ( analysis != null )
			questions = getQuestionnaireQuestionsInOrder();	

		while ( enumeration.hasMoreElements() )
			{
			q_result = (QuestionnaireResult)enumeration.nextElement();
			list.addElement( q_result );
			
			if ( analysis == null )
				continue;
			
			//now add analysis...
			
			analysis.addQuestionnaireResult( q_result );
			responses = q_result.getQuestionnaireResponses();
			
			for ( int i=0; i<questions.size(); i++ )
				{
				q_question = (QuestionnaireQuestion)questions.get( i );
				q_response = (QuestionnaireResponse)responses.get( q_question.getQuestionnaireQuestionId() );
				if ( q_response.isRecorded() )
					analysis.addQuestionnaireResponse( q_question, q_result, q_response );
				}
			
			}

		return list;
		}
	
	
	
	// export XML file containing questions and optionally results and responses
	public void exportXml( boolean include_results, boolean include_responses )
		throws RemoteException, BuildingServerException
	    {
	    int i, j, n;
   		Questionnaire paper = this.getQuestionnaire();
   		Hashtable qtable;
   		List qlist = this.getQuestionnaireQuestionsInOrder();
   		Vector rlist;
   		QuestionnaireQuestion question;
   		QuestionnaireResult result;
   		QuestionnaireResponse response;
	    Enumeration enumeration;
	    
	    
	    if ( paper == null || qlist == null )
            throw new BuildingServerException( "Unable to find questionnaire data." );
            
        try
            {
            File xmlfile = BuildingContext.createTempFile( "bod", ".xml" );
            
            PrintWriter xmlout = new PrintWriter( new FileWriter( xmlfile ) );
            
            xmlout.print( "<?xml version=\"1.0\" standalone=\"no\"?>" );
            xmlout.println();
            xmlout.print( "<!DOCTYPE questestinterop SYSTEM \"http://www.imsproject.org/xml/question/FinalQTIv101/xmla/dtds/QTIcorencdtd/IMS_QTIv1p01.dtd\">" );
            xmlout.println();
            xmlout.print( "<!-- Experimental IMS output -->" );
            
            xmlout.println();
            xmlout.println();

            xmlout.print( "<questestinterop>" );
            //xmlout.print( paper.getQuestionnaireId() );
            //xmlout.print( "\">" );

            xmlout.println();


            for ( i=0; i<qlist.size(); i++ )
                {
                question = (QuestionnaireQuestion)qlist.get( i );

                // ask the question to export itself, allowing composite output
                question.exportXml( xmlout, false );
                }
           /* 
            if ( include_results )
                {
                qtable = this.getQuestionnaireQuestions();
                
                // not too bad to load all the results in one go because there is very
                // little data in the structure
    			rlist = this.getQuestionnaireResults();
                for ( i=0; i<rlist.size(); i++ )
                    {
                    result = (QuestionnaireResult)rlist.elementAt( i );

                    xmlout.print( "\t<QuestionnaireResult id=\"pk" );
                    xmlout.print( result.getQuestionnaireResultId() );
                    xmlout.print( "\">" );
                    xmlout.println();
                   
                    if ( include_responses )
                        {
                        enumeration = QuestionnaireResponse.findQuestionnaireResponses( "questionnaire_result_id = " + result.getQuestionnaireResultId() );
                        while ( enumeration.hasMoreElements() )
                            {
                            response = (QuestionnaireResponse)enumeration.nextElement();
                            question = (QuestionnaireQuestion)qtable.get( response.getQuestionnaireQuestionId() );
                            
                            xmlout.print( "\t\t<QuestionnaireResponse id=\"pk" );
                            xmlout.print( response.getQuestionnaireResponseId() );
                            xmlout.print( "\" questionnairequestionid=\"pk" );
                            xmlout.print( response.getQuestionnaireQuestionId() );
                            xmlout.print( "\">" );
                            xmlout.println();
                            
                            if ( question.getStatementCount()>0 )
                                {
                                xmlout.print( "\t\t\t<Item>" );
                                xmlout.print( response.getItem() );
                                xmlout.print( "</Item>" );
                                xmlout.println();
                                }
                                
                            if ( question.canComment() && response.getComment() !=null )
                                {
                                xmlout.print( "\t\t\t<Comment>" );
                                xmlout.print( response.getComment() );
                                xmlout.print( "</Comment>" );
                                xmlout.println();
                                }
                            
                            xmlout.print( "\t\t</QuestionnaireResponse>" );
                            xmlout.println();
                            }
                        }

                    xmlout.print( "\t</QuestionnaireResult>" );
                    xmlout.println();
                    }
                }
*/
            xmlout.print( "</questestinterop>" );

            xmlout.println();
            xmlout.println();
            
            xmlout.close();
            
            
            this.transferFile( xmlfile.getAbsolutePath(), "qti.xml", "application/octet-stream" );
            }
        catch ( IOException ioex )
            {
            	log.error(ioex.getMessage(),	ioex );
            throw new BuildingServerException( "Problem creating XML file: " + ioex.getMessage() );
            }
	    }
	    

	
	
	public void importXmlQuestions( String file_name )
		throws RemoteException, BuildingServerException
	    {

        try
            {
            //make sure max_ordinal is updated
            getQuestionnaireQuestionIds();
            
            // Parse the input
            XMLReader reader = XMLReaderFactory.createXMLReader( 
            		BuildingContext.getProperty( "xmlrepository.driver", "org.apache.xerces.parsers.SAXParser" ) );
            QuestionnaireImsQtiHandler handler = new QuestionnaireImsQtiHandler( reader );
            reader.setContentHandler( handler );
            
            reader.setProperty( "http://xml.org/sax/properties/lexical-handler", handler );
            reader.setEntityResolver( handler );
            
            File input_file = new File( file_name );
            if ( !input_file.exists() )
                throw new BuildingServerException( "Couldn't open the uploaded file." );
                
            reader.parse( "file:" + input_file );
            
            Vector questions = handler.getQuestions();
            QuestionnaireQuestion question=null, previous_question=null;
            
            for ( int i=0; i<questions.size(); i++ )
                {
                previous_question = question;
                question = (QuestionnaireQuestion)questions.elementAt( i );
                
                if (    previous_question != null &&
                        question.getStatementCount() == 0 && 
                        question.canComment() && 
                        question.getIntroduction().indexOf( "This is the comment box for the previous question." )>=0 )
                    {
                    // merge this question with previous
                    previous_question.setCanComment( true );
                    previous_question.save();
                    //remove current
                    questions.removeElementAt( i );
                    //fix index so we point at next question that has now moved down one place
                    i--;
                    continue;
                    }
                
                question.setQuestionnaireId( getResource().getResourceId() );
		        question.save();
                }
            }
       catch (SAXParseException spe)
            {
            LoggingUtils.logSAXException(log,spe);
            throw new BuildingServerException( "Problem importing XML file: " + spe.getMessage() );
            }
        catch (Throwable t)
            {
            log.error(	t.getMessage(), t );
            throw new BuildingServerException( "Problem importing XML file: " + t.getMessage() );
            }
	    }

    /**
     * Overridden so that we can initialize our corresponding questionnaire
     * instance. Otherwise, we just delegate to the corresponding method in our
     * superclass.
     * @see Questionnaire
     */
    public void setResource( PrimaryKey resource_id ) 
        throws BuildingServerException, RemoteException
        {
        // NOTE: we override this method so as to initialize our questionnaire:
        super.setResource( resource_id );
        this.questionnaire = Questionnaire.findQuestionnaire( 
            getResource().getResourceId() );
        }
	}
	
