package performa.orm;

import oneit.objstore.rdbms.filters.EqualsFilter;
import oneit.utils.BusinessException;
import oneit.utils.filter.CollectionFilter;
import oneit.utils.filter.Filter;
import oneit.utils.parsers.FieldException;
import performa.orm.types.QuestionType;


public class Answer extends BaseAnswer
{
    private static final long   serialVersionUID    =   0L;
    
    // This constructor should not be called
    public Answer ()
    {
        // Do not add any code to this, always put it in initialiseNewObject
    }

    
    @Override
    protected void postInitNewObj() throws BusinessException 
    {
        super.postInitNewObj();
        
        setAnswerNo(0);
    }

    
    @Override
    public void setAnswerNo(Integer newAnswerNo) throws FieldException
    {
        super.setAnswerNo(newAnswerNo);
        
        if(getAnswerNo() != null)
        {
            if(getQuestion() != null && getQuestion().getQuestionType() == QuestionType.IPSATIVE)
            {
                Question    rightQuestion   =   getQuestion().getRightQuestion();

                if(rightQuestion != null)
                {
                    Filter<Answer>  filter  = Answer.SearchByAll().andQuestion(new EqualsFilter<>(rightQuestion));

                    Answer  rightAnswer = CollectionFilter.getFirstMatch(getCandidate().getProfileAssessmentAnswersSet(), filter);

                    if(rightAnswer == null)
                    {
                        rightAnswer  =   Answer.createAnswer(getTransaction());

                        getCandidate().addToProfileAssessmentAnswers(rightAnswer);
                        rightAnswer.setQuestion(rightQuestion);
                    }
                    
                    rightAnswer.setAnswerNo(10 - getAnswerNo());    //Refer below calculation table
                }
            }
        }
    }
    
    /**
     * 
     *  Ipsative answer logic as per Apollo:
     * 
     *  Submitted Left Answer       Final Left Answer       Final Right Answer
     *          1                           9                       1
     *          2                           7                       3
     *          3                           5                       5
     *          4                           3                       7
     *          5                           1                       9
     */
    public int getFinalAnswerValue(int index)
    {
        if(getQuestion() != null && getQuestion().getQuestionType() == QuestionType.IPSATIVE)
        {
            return (10 - ((index * 2) - 1));
        }
        return index;
    }
}