/* ======================================================================
   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.util.Enumeration;
import java.util.List;
import java.util.Vector;

import org.bodington.database.PrimaryKey;
import org.bodington.server.BuildingServerException;
import org.bodington.text.BigString;

/**
 * Class that encapsulates a users response to a questionnaire question. This
 * class pertains to an individual questionnaire question. It includes
 * information such as a reference to the containing questionnaire result, the
 * response comment and the statement that was chosen.
 * @see org.bodington.assessment.QuestionnaireQuestion
 * @see org.bodington.assessment.QuestionnaireResult
 * @author Jon Maber
 * @author Alexis O'Connor
 */
public class QuestionnaireResponse extends org.bodington.sqldatabase.SqlPersistentObject
	{
    /**
     * Constant representing no selection to a single response MCQ question.
     */
    public static final int NO_SINGLE_RESPONSE = 100;
    /**
     * Constant representing no selection to a multiple response MCQ question.
     */
    public static final int NO_MULTIPLE_RESPONSE = 0;
	private PrimaryKey primary_key;
	private PrimaryKey questionnaire_result_id;
	private PrimaryKey questionnaire_question_id;
	private PrimaryKey comment_big_string_id;
	private byte item = NO_SINGLE_RESPONSE;
    private int items = NO_MULTIPLE_RESPONSE;
    private QuestionnaireResult result;
    
    public QuestionnaireResponse()
        {
        }
    
	public static QuestionnaireResponse findQuestionnaireResponse( PrimaryKey key )
	    throws BuildingServerException
	    {
	    return (QuestionnaireResponse)findPersistentObject( key, QuestionnaireResponse.class.getName() );
	    }
	
	public static QuestionnaireResponse findQuestionnaireResponse( String where )
	    throws BuildingServerException
	    {
	    return (QuestionnaireResponse)findPersistentObject( where, QuestionnaireResponse.class.getName() );
	    }
	
	public static Enumeration findQuestionnaireResponses( String where )
	    throws BuildingServerException
	    {
	    return findPersistentObjects( where, QuestionnaireResponse.class.getName() );
	    }
	
	public static Enumeration findQuestionnaireResponses( String where, String order )
	    throws BuildingServerException
	    {
	    return findPersistentObjects( where, order, QuestionnaireResponse.class.getName() );
	    }
	
    public PrimaryKey getPrimaryKey()
    	{
        return primary_key;
    	}

    public void setPrimaryKey(PrimaryKey key)
    	{
        primary_key = key;
        setUnsaved();
    	}

	public PrimaryKey getQuestionnaireResponseId()
		{
		return getPrimaryKey();
		}
		
	public void setQuestionnaireResponseId( PrimaryKey id )
		{
		setPrimaryKey(id);
		}

	/**
     * Get the ID of the containing questionnaire result. This object
     * encapsulates the user response to the questionnaire as a whole.
     * @return the ID of the containing questionnaire result.
     * @see QuestionnaireResult
     * @see #getQuestionnaireResult()
     */
	public PrimaryKey getQuestionnaireResultId()
		{
		return questionnaire_result_id;
		}
		
	/**
     * Set the ID of the containing questionnaire result.
	 * @param id the ID if the containing questionnaire result.
     * @see #getQuestionnaireResultId()
	 */
	public void setQuestionnaireResultId( PrimaryKey id )
		{
		questionnaire_result_id = id;
		}


    /**
     * Get the ID of the corresponding questionnaire question. This is the
     * questionnaire question to which this object is a response.
     * @return the ID of the corresponding questionnaire question.
     * @see QuestionnaireQuestion
     */
	public PrimaryKey getQuestionnaireQuestionId()
		{
		return questionnaire_question_id;
		}
		
    /**
     * Set the ID of the corresponding questionnaire question.
     * @param id the ID of the corresponding questionnaire question.
     * @see #getQuestionnaireQuestionId()
     */
	public void setQuestionnaireQuestionId( PrimaryKey id )
		{
		questionnaire_question_id = id;
		}


    /**
     * Get the index of the statement that the user chose.
     * @return the index of the statement that the user chose.
     * @see QuestionnaireQuestion#getValidStatementIndices()
     */
	public byte getItem()
		{
		return item;
		}
		
	/**
     * Set the index of the statement that the user chose.
	 * @param r the index of the statement that the user chose.
     * @see #getItem()
	 */
	public void setItem( byte r )
		{
		if ( item == r )
			return;
		item = r;
		setUnsaved();
		}
    
    /**
     * Get the selected multiple response items. The actual selections are
     * packed bitwise into a single <code>int</code>. This method is required
     * by the database persistence layer. Programmatically speaking, the method
     * {@link #getSelection() } is easier to use.
     * @return the selected multiple response items.
     * @see #getSelection()
     * @see #getItem()
     * @see QuestionnaireQuestion#isMultipleResponse()
     */
    public int getItems()
        {
        return items;
        }
    
    /**
     * Set the selected multiple response items.
     * @param items the selected multiple response items.
     * @see #getItems()
     */
    public void setItems( int items )
        {
        if ( this.items == items )
            return;
        this.items = items;
        setUnsaved();
        }
    
    /**
     * Set the value of a multiple response item. This method is intended to be
     * used in conjunction with multiple response questions.
     * @param index the index of the value.
     * @param selected the value to set it to.
     * @see QuestionnaireQuestion#isMultipleResponse()
     */
    public void setSelected(int index, boolean selected)
        {
        setItems( setSelected( index, selected, getItems() ) );
        }
    
    /**
     * Get the value of a multiple response item. This method is
     * intended to be used in conjunction with multiple response questions.
     * @param index the index of the value.
     * @return the value of a multiple response item.
     * @see QuestionnaireQuestion#isMultipleResponse()
     */
    public boolean getSelected( int index )
        {
        if ( index < 0 || index > 9)
            throw new IndexOutOfBoundsException();
        int bits = 1 << index;
        return (getItems() & bits) != 0;
        }
    
    /**
     * Get the selected multiple response items. This method is intended to be
     * used in conjunction with multiple response questions. The form of the
     * returned array is that it only contains the indexes of items that have
     * been selected, in order.
     * @return the selected multiple response items.
     * @see QuestionnaireQuestion#isMultipleResponse()
     */
    public byte[] getSelection()
        {
        // Ridiculous, but true!!!
        List bytes = new Vector();
        for( int i = 0; i < 10; i++)
            if( getSelected( i ))
                bytes.add( new Integer( i ));
        
        byte[] selection = new byte[bytes.size()];
        for (int i = 0; i < selection.length; i++)
            selection[i] = ((Integer)bytes.get(i)).byteValue();

        return selection;
        }
    
    /**
     * Set the selected multiple response items.
     * @param selection the selected multiple response items.
     * @see #getSelection()
     */
    public void setSelection( byte[] selection )
        {
        int value = 0; // clean slate.
        for (int i = 0; i < selection.length; i++)
            value = setSelected( selection[i], true, value);
        setItems( value );
        }
    
    /**
     * Set the value of the specified item. The <code>value</code> parameter
     * represents a sequence of <code>yes | no</code> selections, indexed from
     * right to left. The <code>index</code> and <code>selected</code>
     * parameters can be used to turn on or off one if these items at a
     * specified index.
     * @param index the index of the item being specified.
     * @param selected whether the item it is be selected or not.
     * @param value the value to be altered.
     * @return the <code>value</code> parameter after being processed by this
     *         method.
     */
    private static int setSelected( int index, boolean selected, int value )
        {
        if ( index < 0 || index > 9)
            throw new IndexOutOfBoundsException();
        int bits = 1 << index;
        if ( selected == ((value & bits) != 0) )
            return value;
        return value ^ bits;
        }
		
	public PrimaryKey getCommentBigStringId()
		{
		return comment_big_string_id;
		}
		
	public void setCommentBigStringId( PrimaryKey id )
		{
		comment_big_string_id = id;
		setUnsaved();
		}
		
	/**
     * Get the comment string of the corresponding questionnaire question. This
     * is the free text response given to a question.
	 * @return the comment string of the corresponding questionnaire question.
	 * @throws BuildingServerException
     * @see QuestionnaireQuestion#isCanComment()
	 */
	public String getComment()
		throws BuildingServerException
		{
		if ( comment_big_string_id == null )
			return null;
		BigString bstr = BigString.findBigString( comment_big_string_id );
		if ( bstr == null )
			return null;
		return bstr.getString();
		}
		
	/**
     * Set the comment string of the corresponding questionnaire question.
     * @param s the comment string of the corresponding questionnaire question.
     * @throws BuildingServerException
     * @see #getComment()
     */
	public void setComment( String s )
		throws BuildingServerException
		{
		BigString bstr=null;

		if ( comment_big_string_id == null && s == null )
			return;
			
		if ( comment_big_string_id != null && s == null )
			{
			bstr = BigString.findBigString( comment_big_string_id );
			if ( bstr!=null )
				{
				if ( !bstr.isUnsaved() )
					bstr.delete();
				}
			comment_big_string_id = null;
			setUnsaved();
			}
			
		if ( comment_big_string_id != null )
			bstr = BigString.findBigString( comment_big_string_id );
		if ( bstr == null )
			{
			bstr = new BigString();
			bstr.setString( s );
			bstr.save();
			comment_big_string_id = bstr.getBigStringId();
			setUnsaved();
			return;
			}

		bstr.setString( s );
		bstr.save();
		}
    
    /**
     * Get the containing questionnaire result. This object encapsulates the
     * user response to the questionnaire as a whole.
     * @return the containing questionnaire result.
     * @see #getQuestionnaireResultId()
     */
    public QuestionnaireResult getQuestionnaireResult() 
        throws BuildingServerException
        {
        if (result == null)
            {
            result = QuestionnaireResult.findQuestionnaireResult(
                getQuestionnaireResultId());
            }
        return result;
        }
    
    /**
     * Get the value of {@link #getItem()} as a string.
     * @return the value of {@link #getItem()} as a string.
     * @see #itemToString(byte)
     * @see #getItem()
     */
    public String itemToString()
        {
        return itemToString( getItem() );
        }
    
    /**
     * Get the specified item as a string. This method always
     * returns a non-null result. If the user selected a multiple-choice item,
     * then this method will return a value between <code>A</code> to
     * <code>J</code> (inclusive). Otherwise, it will be an empty string.
     * @param item the value of the item.
     * @return the input parameter as a string.
     * @see #getItem()
     * @see #getItems()
     */
    public static String itemToString( byte item )
        {
        if ( item < 0 || item > 9)
            return "";
        
        return String.valueOf( (char)('A' + item) );
        }
    
    /**
     * Get the value of {@link #getComment()} as a string. This method always
     * returns a non-null result.
     * @return the value of {@link #getComment()} as a string.
     * @see #getComment()
     */
    public String commentToString()
        {
        try
            {
            String s = getComment();
            return (s == null) ? "" : s;
            }
        catch ( BuildingServerException e )
            {
            return "";
            }
        }
	}
