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

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.bodington.assessment.ims.McqImsQtiHandler;
import org.bodington.database.PrimaryKey;
import org.bodington.server.*;
import org.bodington.server.events.ExportEvent;
import org.bodington.server.realm.User;
import org.bodington.text.BigString;
import org.bodington.xml.ClasspathEntityResolver;
import org.bodington.xml.XMLUtils;

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." );
        if ( McqResponse.findMcqResponses("mcq_question_id = "+ id).hasMoreElements())
            throw new BuildingServerUserException("Can't remove question as it has results.");

		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 (IMS QTI) containing questions.
	 * Calling method is responsible for closing the OutputStream passed in as a parameter.
	 */
	
	public void exportXML( OutputStream stream )
	throws BuildingServerException
	{
		int i;
		McqPaper paper = this.getMcqPaper();
		Vector qlist = this.getMcqQuestionsInOrder();
		McqQuestion question;

		if ( paper == null || qlist == null )
			throw new BuildingServerException( "Unable to find MCQ data." );

		try
		{          
			PrintWriter xmlout = new PrintWriter( new BufferedWriter (new OutputStreamWriter( stream, "UTF8" )));

			xmlout.print( "<?xml version=\"1.0\" standalone=\"no\"?>" );
			xmlout.println();
			xmlout.print( "<!DOCTYPE questestinterop SYSTEM \"ims_qtiasiv1p2p1.dtd\">" );

			xmlout.println();
			xmlout.println();

			xmlout.println( "<questestinterop>" );
			xmlout.print( "<assessment ident=\"" + paper.getResourceId() + "\"");
			xmlout.println( " title=\"" + paper.getTitle() + "\">" );

			xmlout.println( "\t<presentation_material>");
			xmlout.println( "\t\t<flow_mat>");
			xmlout.println( "\t\t\t<material>");
			xmlout.print( "\t\t\t\t<mattext><![CDATA[");
			xmlout.print(paper.getDescription());
			xmlout.println("]]></mattext>");
			xmlout.println( "\t\t\t</material>");
			xmlout.println( "\t\t</flow_mat>");
			xmlout.println( "\t</presentation_material>");

			xmlout.println( "\t<section ident=\"default\">");

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

			xmlout.println( "\t</section>" );
			xmlout.println( "</assessment>" );
			xmlout.println( "</questestinterop>" );
			xmlout.println();
			xmlout.flush();

			ExportEvent event = new ExportEvent(ExportEvent.EVENT_EXPORT_ASSESSMENT, paper);
			event.save();

		}
		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 = XMLUtils.getXMLReader();		
            		
            McqImsQtiHandler handler = new McqImsQtiHandler( reader );
            reader.setContentHandler( handler );
            reader.setProperty( "http://xml.org/sax/properties/lexical-handler", handler );
            
            ClasspathEntityResolver resolver = new ClasspathEntityResolver( handler.getClass() );
            reader.setEntityResolver( resolver );
            
            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 );

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