package performa.form;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
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 oneit.utils.DateDiff;
import performa.intercom.utils.IntercomUtils;
import performa.orm.CompanyUser;
import performa.orm.Job;
import performa.orm.types.JobStatus;


public class SaveJobFP extends SaveFP 
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest  request =   submission.getRequest();
        Job                 job     =   process.getAttribute("Job") != null ? (Job) process.getAttribute("Job") : (Job) request.getAttribute("Job");
        Boolean             openJob =   (Boolean) request.getAttribute("openJob");
        
        LogMgr.log(Job.LOG, LogLevel.PROCESSING1,"In SaveJobFP saving job : ", job );

        Job oldJob  = (Job) job.getEarliestBackup();

        if(openJob==Boolean.TRUE)
        {
            job.setJobStatus(JobStatus.OPEN);
            
            LogMgr.log(Job.LOG, LogLevel.PROCESSING1,"Job status changed as Open. ", job );
        }
        
        if(oldJob != null && oldJob.getJobStatus() == JobStatus.DRAFT && job.getJobStatus() == JobStatus.OPEN)
        {
            job.setApplyBy(DateDiff.add(DateDiff.getToday(), Calendar.DATE, 30));
            job.setOpenDate(new Date());
        }
        
        if(job.getJobStatus() == JobStatus.OPEN && job.getShortenedURL() == null)
        {
            job.createShortenedURL();
        }
        
        // restarting process as job count needs to be updated to intercom
        process.completeAndRestart();
        
        SecUser     secUser     =   SecUser.getTXUser(process.getTransaction());
        CompanyUser companyUser =   secUser.getExtension(CompanyUser.REFERENCE_CompanyUser);

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