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.security.SecUser;
import oneit.servlets.forms.RedisplayResult;
import oneit.servlets.forms.SubmissionDetails;
import oneit.servlets.forms.SuccessfulResult;
import oneit.servlets.process.ORMProcessState;
import oneit.servlets.process.SaveFP;
import oneit.utils.BusinessException;
import performa.intercom.utils.IntercomUtils;
import performa.orm.CompanyUser;
import performa.orm.JobApplication;

public class ChangeApplicationStatusFP extends SaveFP 
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request         =   submission.getRequest();
        JobApplication      jobApplication  =   (JobApplication) request.getAttribute("JobApplication");
        
        LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1,"In ChangeApplicationStatusFP changing status of Job Application : ", jobApplication );

        if(jobApplication.getWorkFlow() == null)
        {
            LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1,"In ChangeApplicationStatusFP , no workflow set : ", jobApplication.getWorkFlow() );
            
            return RedisplayResult.getInstance();
        }
        
        jobApplication.setApplicationStatus(jobApplication.getWorkFlow().getApplicationStatus());
        
        LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1,"In ChangeApplicationStatusFP Job Application Status successfully changed : ", 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.getCompany() != null)
        {
            IntercomUtils.updateCompany(companyUser.getCompany());
        }
        
        return super.processForm(process, submission, params);
    }
}