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.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;
import performa.orm.types.AppProcessOption;
import performa.orm.types.ApplicationStatus;

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.getAppProcessOption() == AppProcessOption.TO_SHORTLIST)
        {
            jobApplication.setApplicationStatus(ApplicationStatus.SHORTLISTED);
        }
        else if(jobApplication.getAppProcessOption() == AppProcessOption.REMOVE_FROM_SHORTLIST)
        {
            jobApplication.setApplicationStatus(ApplicationStatus.SUBMITTED);
        }
        else if(jobApplication.getAppProcessOption() == AppProcessOption.TO_UNSUITABLE)
        {
            jobApplication.setApplicationStatus(ApplicationStatus.UNSUITABLE);
        }
        else if(jobApplication.getAppProcessOption() == AppProcessOption.REMOVE_FROM_UNSUITABLE)
        {
            jobApplication.setApplicationStatus(ApplicationStatus.SUBMITTED);
        }
        
        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);
    }
}