/* ======================================================================
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.Vector;
import java.util.Enumeration;
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.McqImsQtiHandler;
import org.bodington.database.PrimaryKey;
import org.bodington.logging.LoggingUtils;
import org.bodington.server.*;
import org.bodington.server.realm.User;
import org.bodington.text.BigString;

public class McqPaperSessionImpl
	extends org.bodington.server.SingleResourceSession 
	implements McqPaperSession 
	{
    
    private static Logger log = Logger.getLogger(McqPaperSessionImpl.class);
	int max_ordinal=0;
	
	public McqPaperSessionImpl()
		{
		super();
		}
	

	public McqPaper getMcqPaper() throws BuildingServerException
		{
		McqPaper paper = McqPaper.findMcqPaper( getResource().getResourceId() );
		return paper;
		}
		
	public void setOnceOnly( boolean b ) throws BuildingServerException
		{
		McqPaper paper = McqPaper.findMcqPaper( getResource().getResourceId() );
		if ( paper == null )
			throw new BuildingServerException( "Can't find MCQ paper." );
		paper.setOnceOnly( b );
		paper.save();
		}
	
	public void setMarkWitheld( boolean b ) throws BuildingServerException
		{
		McqPaper paper = McqPaper.findMcqPaper( getResource().getResourceId() );
		if ( paper == null )
			throw new BuildingServerException( "Can't find MCQ paper." );
		paper.setMarkWitheld( b );
		paper.save();
		}
	
	public void setDeadline( Timestamp t ) throws BuildingServerException
		{
		McqPaper paper = McqPaper.findMcqPaper( getResource().getResourceId() );
		if ( paper == null )
			throw new BuildingServerException( "Can't find MCQ paper." );
		paper.setDeadline( t );
		paper.save();
		}
	
	public Vector getMcqQuestionIds() throws BuildingServerException
		{
		Vector list = new Vector();
		
		McqQuestion question;
		Enumeration enumeration = McqQuestion.findMcqQuestions( "resource_id = " + getResource().getResourceId().toString(), "ordinal" );
		while ( enumeration.hasMoreElements() )
			{
			question = (McqQuestion)enumeration.nextElement();
			list.addElement( question.getMcqQuestionId() ); 
			if ( question.getOrdinal() > max_ordinal )
				max_ordinal = question.getOrdinal();
			}
		
		return list;
		}
	
	public Hashtable getMcqQuestions() throws BuildingServerException
		{
		Hashtable table = new Hashtable();
		
		McqQuestion question;
		Enumeration enumeration = McqQuestion.findMcqQuestions( "resource_id = " + getResource().getResourceId().toString() );
		while ( enumeration.hasMoreElements() )
			{
			question = (McqQuestion)enumeration.nextElement();
			table.put( question.getMcqQuestionId(), question );
			if ( question.getOrdinal() > max_ordinal )
				max_ordinal = question.getOrdinal();
			}
		
		return table;
		}
	
	public Vector getMcqQuestionsInOrder() throws BuildingServerException
		{
		Vector list = new Vector();
		
		McqQuestion question;
		Enumeration enumeration = McqQuestion.findMcqQuestions( "resource_id = " + getResource().getResourceId().toString(), "ordinal" );
		while ( enumeration.hasMoreElements() )
			{
			question = (McqQuestion)enumeration.nextElement();
			list.addElement( question ); 
			if ( question.getOrdinal() > max_ordinal )
				max_ordinal = question.getOrdinal();
			}
		
		return list;
		}
	
	public Hashtable getStrings() throws BuildingServerException
		{
		Hashtable table = getMcqQuestions();
		
		McqQuestion question;
		BigString big_string;
		PrimaryKey id;
		Enumeration enumeration = table.elements();
		while ( enumeration.hasMoreElements() )
			{
			question = (McqQuestion)enumeration.nextElement();
			id = question.getQuestionBigStringId();
			big_string = BigString.findBigString( id );
			table.put( id, big_string.getString() );
			}
			
		return table;
		}

	public McqQuestion createQuestion() throws BuildingServerException
		{
		McqQuestion question = new McqQuestion();
		
		question.setResourceId( getResource().getResourceId() );
		question.setQuestion( "Question text here." );
		question.setExplanation( "Explanatory text here." );
		for ( int i=0; i<5; i++ )
			{
			question.setStatement( i, "Option text here." );
			question.setAnswer( i, true );
			}
		question.setOrdinal( max_ordinal+100 );
		question.setFlags( (byte)0 );
		question.save();
		
		return question;
		}
	
	public void removeQuestion( PrimaryKey id ) throws BuildingServerException
		{
		McqQuestion question =  McqQuestion.findMcqQuestion( id );
		if ( question == null )
			throw new BuildingServerException( "Question not found." );

		if ( !question.getResourceId().equals( getResource().getResourceId() ) )
			throw new BuildingServerException( "Question doesn't belong in this MCQ paper." );

		question.delete();
		}
	
	public void changeQuestion( PrimaryKey id, McqQuestion model )
		throws BuildingServerException
		{
		McqQuestion question =  McqQuestion.findMcqQuestion( id );
		if ( question == null )
			throw new BuildingServerException( "Question not found." );

		if ( !question.getResourceId().equals( getResource().getResourceId() ) )
			throw new BuildingServerException( "Question doesn't belong in this MCQ paper." );

		for ( int i=0; i<5; i++ )
			{
			question.setAnswer( i, model.getAnswer( i ) );
			}
		question.setOrdinal( model.getOrdinal() );
		question.setFlags( model.getFlags() );
		question.save();

		if ( question.getOrdinal() > max_ordinal )
			max_ordinal = question.getOrdinal();
		}
	
	public void changeQuestionText( PrimaryKey qid, PrimaryKey tid, String new_text )
		throws BuildingServerException
		{
		McqQuestion question =  McqQuestion.findMcqQuestion( qid );
		if ( question == null )
			throw new BuildingServerException( "Question not found." );
			
		if ( !question.getResourceId().equals( getResource().getResourceId() ) )
			throw new BuildingServerException( "Question doesn't belong in this MCQ paper." );

		boolean found = false;
		found = found || tid.equals( question.getQuestionBigStringId() );
		found = found || tid.equals( question.getExplanationBigStringId() );
		found = found || tid.equals( question.getStatementABigStringId() );
		found = found || tid.equals( question.getStatementBBigStringId() );
		found = found || tid.equals( question.getStatementCBigStringId() );
		found = found || tid.equals( question.getStatementDBigStringId() );
		found = found || tid.equals( question.getStatementEBigStringId() );

		if ( !found )
			throw new BuildingServerException( "Can't identify qhich part of question to edit." );

		BigString big = BigString.findBigString( tid );
		big.setString( new_text );
		big.save();
		}
	

	public McqResult record( PrimaryKey[] mcq_question_ids, int[][] responses )
		throws BuildingServerException
		{
		Hashtable mcq_questions = this.getMcqQuestions();
		
		McqQuestion mcq_question;
		McqResponse[] mcq_response = new McqResponse[responses.length];
		McqResult mcq_result = new McqResult();
		mcq_result.setResourceId( this.getResource().getResourceId() );
		mcq_result.setUserId( getUserId() );
		mcq_result.setWhenDone( new Timestamp( System.currentTimeMillis() ) );
		mcq_result.setWhenMarked( new Timestamp( System.currentTimeMillis() ) );

		int total_available=0, total_right=0, total_wrong=0, total_lost=0;
		int available, right, wrong, lost;
		boolean answer[] = new boolean[5];
		
		for ( int i=0; i< mcq_question_ids.length; i++ )
			{
			mcq_question = (McqQuestion)mcq_questions.get( mcq_question_ids[i] );
			mcq_response[i] = new McqResponse();
			mcq_response[i].setMcqQuestionId( mcq_question_ids[i] );
			for ( int j=0; j<5; j++ )
				{
				answer[j] = mcq_question.getAnswer( j );
				mcq_response[i].setResponse( j, responses[i][j] );
				}
			
			mcq_response[i].mark( mcq_question );			
				
			total_available	+=mcq_response[i].getAvailable();
			total_right		+=mcq_response[i].getRight();
			total_wrong		+=mcq_response[i].getWrong();
			total_lost		+=mcq_response[i].getDeductions();
			
			
			}

		mcq_result.setAvailable(	total_available );
		mcq_result.setRight(		total_right 	);
		mcq_result.setWrong(		total_wrong 	);
		mcq_result.setDeductions(	total_lost		);
		mcq_result.save();
		for ( int i=0; i< mcq_response.length; i++ )
			{
			mcq_response[i].setMcqResultId( mcq_result.getMcqResultId() );
			mcq_response[i].save();
			}
		
		
		return mcq_result;
		}
	
	public McqResult getMcqResult( PrimaryKey rid )
		throws BuildingServerException
		{
		McqResult mcq_result = McqResult.findMcqResult( rid );
		if ( mcq_result.getResourceId().equals( this.getResource().getResourceId() ) )
			return mcq_result;
		return null;
		}

	public Hashtable getMcqResponses( PrimaryKey rid )
		throws BuildingServerException
		{
		McqResult mcq_result = getMcqResult( rid );
		if ( mcq_result == null )
			return null;
		
		Hashtable table = new Hashtable();
		Enumeration enumeration = McqResponse.findMcqResponses( "mcq_result_id = " + rid );
		McqResponse mcq_response;
			
		while ( enumeration.hasMoreElements() )
			{
			mcq_response= (McqResponse)enumeration.nextElement();
			table.put( mcq_response.getMcqQuestionId(), mcq_response );
			}

		return table;
		}

	public Vector getResultsOfUser() throws BuildingServerException
		{
		Vector list = new Vector();
		Enumeration enumeration = McqResult.findMcqResults( 
					"resource_id = " + this.getResource().getResourceId() + " AND user_id = " + getUserId(),
					"when_done" );
			
		while ( enumeration.hasMoreElements() )
			list.addElement( enumeration.nextElement() );

		return list;
		}

	public Hashtable getMcqUsers() throws BuildingServerException
		{
		Hashtable users= new Hashtable();
		User user;
		
		Enumeration enumeration = 
			User.findUsers(
				"user_id IN (SELECT user_id FROM mcq_results WHERE resource_id = " +
				getResource().getResourceId() +
				")",
				"surname, initials" );
		
		while ( enumeration.hasMoreElements() )
			{
			user = (User)enumeration.nextElement();
			users.put( user.getUserId(), user );
			}
		
		return users;
		}


	
	// returns enumeration of results found and if analysis is non null it is filled in with
	// statistical analysis.
	public Vector analyse( String where_clause, boolean first_attempt, Vector users, Vector alt_marks, McqAnalysis analysis )
		throws BuildingServerException
		{
		Vector list = new Vector();
		Enumeration enumeration = McqResult.findMcqResults( where_clause, "when_done" );
			
		McqResult mcq_result;
		McqResponse mcq_response;
		McqQuestion mcq_question;
		PrimaryKey user_id;
		Hashtable responses;
		Vector questions=null;
		Hashtable previous_user_ids = new Hashtable();
		
		if ( analysis != null )
			questions = getMcqQuestionsInOrder();	

		while ( enumeration.hasMoreElements() )
			{
			mcq_result = (McqResult)enumeration.nextElement();
			user_id = mcq_result.getUserId();

            if ( first_attempt )
                {
                if ( previous_user_ids.containsKey( user_id ) )
				    continue;
				previous_user_ids.put( user_id, user_id );
				}
			
			list.addElement( mcq_result );
			
			if ( analysis == null )
				continue;
			
			//now add analysis...
			
			analysis.addMcqResult( mcq_result );
			
			if ( analysis.getDepth() < analysis.SUMMARY_AND_QUESTION )
				continue;
			
			responses = getMcqResponses( mcq_result.getMcqResultId() );
			
			for ( int i=0; i<questions.size(); i++ )
				{
				mcq_question = (McqQuestion)questions.elementAt( i );
				mcq_response = (McqResponse)responses.get( mcq_question.getMcqQuestionId() );
				if ( mcq_response != null )
					analysis.addMcqResponse( mcq_question, mcq_result, mcq_response );
				}
			
			}

		return list;
		}
		
		
	// export XML file containing questions and optionally results and responses
	public void exportXml( boolean include_results, boolean include_responses )
		throws BuildingServerException
	    {
	    int i, j, n;
   		McqPaper paper = this.getMcqPaper();
   		Hashtable qtable;
   		Vector qlist = this.getMcqQuestionsInOrder();
   		McqQuestion question;
	    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 OutputStreamWriter( new FileOutputStream( xmlfile ), "UTF8" ) );
            
            xmlout.print( "<?xml version=\"1.0\" standalone=\"no\"?>" );
            xmlout.println();
            xmlout.print( "<!DOCTYPE questestinterop SYSTEM \"ims_qtiasiv1p2.dtd\">" );
            xmlout.println();
            xmlout.print( "<!-- Experimental IMS output -->" );
            
            xmlout.println();
            xmlout.println();

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

            xmlout.println();


            for ( i=0; i<qlist.size(); i++ )
                {
                question = (McqQuestion)qlist.elementAt( i );

                // ask the question to export itself, allowing composite output
                question.exportXml( xmlout );
                }
            xmlout.print( "</questestinterop>" );

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

	    
	    
	    
	    
	public void importXmlQuestions( String file_name )
		throws BuildingServerException
	    {

        try
            {
            //make sure max_ordinal is updated
            getMcqQuestionIds();
            
            // Parse the input
            XMLReader reader = XMLReaderFactory.createXMLReader(
            // WebLearn (modification) [24/01/05] Alexis O'Connor <crimson> 
            		BuildingContext.getProperty( "xmlrepository.driver", "org.apache.xerces.parsers.SAXParser" ) );
            // <<<--- WebLearn modification.		
            		
            McqImsQtiHandler handler = new McqImsQtiHandler( 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." );

            FileInputStream instream = new FileInputStream( input_file );

            InputSource source = new InputSource( instream );
            source.setSystemId(this.getClass()
                .getResource("ims_qtiasiv1p2.dtd").toString());

            
            reader.parse( source );
            
            instream.close();
            
            Vector questions = handler.getQuestions();
            McqQuestion question=null;
            
            for ( int i=0; i<questions.size(); i++ )
                {
                question = (McqQuestion)questions.elementAt( i );
                question.setResourceId( getResource().getResourceId() );
		        question.setOrdinal( max_ordinal+100 );
		        max_ordinal+=100;
		        question.save();
                }
            }
       catch (SAXParseException 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() );
        }
	    }
	    
	    

		
	}
	
