package performa.orm;

import oneit.objstore.rdbms.filters.EqualsFilter;
import oneit.utils.filter.CollectionFilter;
import oneit.utils.filter.Filter;
import oneit.utils.parsers.FieldException;


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

    
    @Override
    public void preCommit(boolean willBeStored) throws Exception 
    {
        super.preCommit(willBeStored);
        
        if(this.getAnswerNo()==null)
        {
            this.delete();
        }
    }
    
    
    @Override
    protected void postAnswerNoChange() throws FieldException 
    {
        super.postAnswerNoChange();
        
        if(getQuestion() != null)
        {
            Question    rightQuestion   =   getQuestion().getRightQuestion();

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

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

                if(rightAnswer!=null)
                {
                    rightAnswer.setAnswerNo(calculateRightAnswerNo());
                }
            }
        }
    }
    
    
    public Integer calculateRightAnswerNo()
    {
        if(getAnswerNo()!=null)
        {
            return  MAX_ANSWER_NO - getAnswerNo();
        }
        return null;
    }
}