package performa.form;

import oneit.servlets.forms.*;
import oneit.utils.*;
import performa.orm.CultureCriteria;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.objstore.StorageException;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.process.ORMProcessState;
import performa.orm.Job;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.servlets.process.ProcessRedirectResult;
import oneit.servlets.process.SaveFP;

public class ProcessCultureFP 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();
        Job                 job             =   (Job) process.getAttribute("Job");
        boolean             fromJobMatch    =   request.getAttribute("fromJobMatch") != null ? (boolean) request.getAttribute("fromJobMatch"): false;
        boolean             fromCulture     =   request.getAttribute("fromCulture") != null ? (boolean) request.getAttribute("fromCulture"): false;
        boolean             fromAssessment  =   request.getAttribute("fromAssessment") != null ? (boolean) request.getAttribute("fromAssessment"): false;
        
        Debug.assertion(job != null, "No job found . Call from " + getClass().getName());
        
        
        if(fromJobMatch)
        {
            BusinessObjectParser.assertFieldCondition(job.getILOJobTitle() != null, job , Job.SINGLEREFERENCE_ILOJobTitle, "mandatory", exceptions, true, request);
        }
                
        if(fromCulture)
        {
            for(CultureCriteria criteria: job.getCultureCriteriasSet())
            {
                if(criteria.getIsApplicable())
                {
                    BusinessObjectParser.assertFieldCondition(criteria.getCultureElementRating() != null, criteria , CultureCriteria.SINGLEREFERENCE_CultureElementRating, "mandatory", exceptions, true, request);

                    BusinessObjectParser.assertFieldCondition(criteria.getImportance() != null, criteria , CultureCriteria.FIELD_Importance, "mandatory", exceptions, true, request);
                }
            }
        }
        
        if(fromAssessment)
        {
            if (job.getIncludeAssessmentCriteria())
            {
                BusinessObjectParser.assertFieldCondition(job.getAssessmentCriteriasCount() > 0, job , Job.FIELD_IncludeAssessmentCriteria, "atleastOneRequirement", exceptions, true, request);
            }
        }
    }
}