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.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.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             =   ObjectTransaction.getTransaction();
        JobApplication      jobApplication      =   (JobApplication) process.getAttribute("JobApplication");
        boolean             fromRequirements    =   request.getAttribute("fromRequirements") != null ? (boolean) request.getAttribute("fromRequirements"): false;
        boolean             fromCoverLetter     =   request.getAttribute("fromCoverLetter") != null ? (boolean) request.getAttribute("fromCoverLetter"): false;
        
        Debug.assertion(jobApplication != null, "No jobApplication found . Call from " + getClass().getName());
        
        if(jobApplication.isIncludeAssessmentCriteria() && fromRequirements)
        {
            JobApplication  application =   jobApplication.getInTransaction(objTran);

            BusinessObjectParser.assertFieldCondition(jobApplication.getJob().getAssessmentCriteriasCount() == application.getAssessmentCriteriaAnswersCount(), jobApplication, JobApplication.FIELD_ObjectID, "completeAssessment", exceptions, true, request);
        }
        
        if(fromCoverLetter)
        {
            BusinessObjectParser.assertFieldCondition(jobApplication.getCV() != null , jobApplication, JobApplication.FIELD_CV, "mandatory", exceptions, true, request);
            BusinessObjectParser.assertFieldCondition(jobApplication.getCoverLetter() != null , jobApplication, JobApplication.FIELD_CoverLetter, "mandatory", exceptions, true, request);
        }
    }
}