package performa.search;

import oneit.objstore.BaseBusinessClass;
import oneit.objstore.rdbms.filters.EqualsFilter;
import performa.orm.Answer;
import performa.orm.AssessmentCriteriaAnswer;
import performa.orm.CultureCriteriaAnswer;
import performa.orm.JobApplication;


public class SearchApplicant extends BaseSearchApplicant
{
    private static final long serialVersionUID = 0L;
    
    // This constructor should not be called
    public SearchApplicant ()
    {
        // Do not add any code to this, always put it in initialiseNewObject
    }
    
    @Override
    public BaseBusinessClass[] doSearch() 
    {
        JobApplication[] appResults = JobApplication.SearchByDetails()
                                                .byName(getDetails())
                                                .andJob(new EqualsFilter<>(getJob()))
                                                .search(getTransaction());
        
        // add to make sure to have any new ones
        if(getJob() != null)
        {
            for(JobApplication app : appResults)
            {
                Answer[]    answers =   Answer.SearchByAll().andCandidate(new EqualsFilter<>(app.getCandidate())).search(getTransaction());
                
                for (Answer answer: answers)
                {
                    app.getCandidate().addToProfileAssessmentAnswers(answer);
                }
                
                AssessmentCriteriaAnswer[]  requirements    =   AssessmentCriteriaAnswer.SearchByAll().andJobApplication(new EqualsFilter<>(app)).search(getTransaction());
                
                for (AssessmentCriteriaAnswer requirement: requirements)
                {
                    app.addToAssessmentCriteriaAnswers(requirement);
                }
                
                CultureCriteriaAnswer[] cultures =   CultureCriteriaAnswer.SearchByAll().andCandidate(new EqualsFilter<>(app.getCandidate())).search(getTransaction());
                
                for (CultureCriteriaAnswer culture: cultures)
                {
                    app.getCandidate().addToCultureCriteriaAnswers(culture);
                }
                
                getJob().addToJobApplications(app);
            }
        }
        
        return appResults;
    }
}