package performa.form;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.LogLevel;
import oneit.logging.LogMgr;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessFormProcessor;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.ProcessRedirectResult;
import oneit.utils.BusinessException;
import oneit.utils.MultiException;
import performa.orm.Job;
import performa.utils.Utils;


public class NavigateToCreateJobFP extends ORMProcessFormProcessor
{
    @Override
    protected Map validate(SubmissionDetails submission, MultiException exceptions) 
    {
        HttpServletRequest  request =   submission.getRequest();
        Job                 job     =   (Job) request.getAttribute ("Job");
        
        if(job != null && job.isTrue(job.getFromTemplate()))
        {
            if(job.getHiringTeam().showHasClientSupport())
            {
                BusinessObjectParser.assertFieldCondition(job.getClient() != null , job, Job.SINGLEREFERENCE_Client, "mandatory", exceptions, true, request);
            }
            
            BusinessObjectParser.assertFieldCondition(job.getAssessmentTemplate() != null , job, Job.SINGLEREFERENCE_AssessmentTemplate, "mandatory", exceptions, true, request);
        }
        
        return super.validate(submission, exceptions);
    }

    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map map) throws BusinessException, StorageException 
    {
        HttpServletRequest  request     =   submission.getRequest();
        Job                 job         =   (Job) request.getAttribute ("Job");
        String              nextPage    =   (String) request.getAttribute("nextPage");
        
        LogMgr.log(Job.LOG, LogLevel.PROCESSING1,"In NavigateToCreateJobFP navigating to create job with from template : ", job.getFromTemplate());

        if(job.isTrue(job.getFromTemplate()))
        {
            if(job.getAssessmentTemplate() == null)
            {
                throw new BusinessException("Please select a template before starting the job");
            }
            
            LogMgr.log(Job.LOG, LogLevel.PROCESSING1, "Inside NavigateToCreateJobFP for ", job, " load from template:", job.getAssessmentTemplate());

            Utils.setupJobFromTemplate(job, job.getAssessmentTemplate(), process.getTransaction());

            LogMgr.log(Job.LOG, LogLevel.PROCESSING1, "NavigateToCreateJobFP completed for ", job);
        }
        
        return new ProcessRedirectResult (nextPage, new String[]{});
    }
}
