package performa.form;

import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.*;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.security.SecUser;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import static oneit.servlets.process.SaveFP.completeProcessRestartAndRestoreAttribs;
import oneit.utils.*;
import performa.intercom.utils.IntercomUtils;
import performa.orm.*;
import performa.orm.types.ApplicationStatus;
import performa.utils.AnalysisEngine;
 

public class CompleteApplicationFP extends SaveFP
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException 
    {
        HttpServletRequest  request         =   submission.getRequest();
        JobApplication      jobApplication  =   (JobApplication) process.getAttribute("JobApplication");
        
        jobApplication.setApplicationStatus(ApplicationStatus.SUBMITTED);
        jobApplication.setSubmittedDate(new Date());
        
        AnalysisEngine.analyseAnswers(jobApplication.getCandidate(), jobApplication.getJob().getLevel(), jobApplication.getCompletedAnswers());
        
        //TODO: set application status as UNSUITABLE if not scored
        if(false)
        {
            jobApplication.setApplicationStatus(ApplicationStatus.UNSUITABLE);
        }
        
        LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING2, "Job Application Completed", jobApplication);
        
        // restarting process as custom attributes needs to be updated to intercom
        completeProcessRestartAndRestoreAttribs(process, request);
        
        SecUser     secUser     =   SecUser.getTXUser(process.getTransaction());
        CompanyUser companyUser =   secUser.getExtension(CompanyUser.REFERENCE_CompanyUser);

        // Update company in intercom
        if(companyUser != null && companyUser.getCompany() != null)
        {
            IntercomUtils.updateCompany(companyUser.getCompany());
        }
        
        return super.processForm(process, submission, params);
    }

    
    @Override
    public void validate(ORMProcessState process, SubmissionDetails submission, MultiException exceptions, Map params) throws StorageException 
    {
        HttpServletRequest  request         =   submission.getRequest();
        JobApplication      jobApplication  =   (JobApplication) process.getAttribute("JobApplication");
        
        if(!jobApplication.cultureCompleted())
        {
            BusinessObjectParser.assertFieldCondition(jobApplication.getCandidate().getCultureCriteriaAnswersCount()>0, jobApplication, jobApplication.FIELD_ObjectID, "completeCulture", exceptions, true, request);
        }
        
        super.validate(process, submission, exceptions, params);
    }
}