package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.objstore.rdbms.filters.EqualsFilter;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.ProcessRedirectResult;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import oneit.utils.Debug;
import oneit.utils.MultiException;
import performa.orm.AssessmentCriteriaAnswer;
import performa.orm.JobApplication;


public class ValidateApplicationFP extends SaveFP
{

    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        return new ProcessRedirectResult((String) submission.getRequest().getAttribute("nextPage"),  new String[0]);
    }
    
    
    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException
    {
        super.validate(process, submission, exceptions, params);
        
        HttpServletRequest  request             =   submission.getRequest();
        ObjectTransaction   objTran             =   process.getTransaction();
        JobApplication      application         =   process.getAttribute("JobApplication") != null ? (JobApplication) process.getAttribute("JobApplication") : (JobApplication)request.getAttribute("JobApplication");
        JobApplication      jobApplication      =   application.getInTransaction(objTran);
        boolean             fromRequirements    =   request.getAttribute("fromRequirements") != null ? (boolean) request.getAttribute("fromRequirements"): false;
        
        Debug.assertion(jobApplication != null, "No jobApplication found . Call from " + getClass().getName());

        if(jobApplication.isIncludeAssessmentCriteria() && fromRequirements)
        {
            AssessmentCriteriaAnswer[]  criteria =   AssessmentCriteriaAnswer.SearchByAll().andJobApplication(new EqualsFilter<>(jobApplication)).search(objTran);

            BusinessObjectParser.assertFieldCondition(jobApplication.getJob().getAssessmentCriteriasCount() == criteria.length, application, JobApplication.FIELD_ObjectID, "completeAssessment", exceptions, true, request);
        }
    }
}