package performa.form;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import oneit.logging.*;
import oneit.objstore.StorageException;
import oneit.objstore.parser.BusinessObjectParser;
import oneit.objstore.utils.ObjstoreUtils;
import oneit.servlets.forms.*;
import oneit.servlets.process.*;
import oneit.utils.*;
import oneit.utils.Debug;
import oneit.utils.filter.*;
import performa.orm.*;
import performa.orm.types.StageType;


public class BulkUpdateFP extends SaveFP 
{
    @Override
    public SuccessfulResult processForm(ORMProcessState process, SubmissionDetails submission, Map params) throws BusinessException, StorageException
    {
        HttpServletRequest      request         =   submission.getRequest();
        List<JobApplication>    applications    =   ObjstoreUtils.getActioned(request, "IsSelected", process.getTransaction(), JobApplication.REFERENCE_JobApplication);
        Job                     job             =   (Job) request.getAttribute("Job");

        Debug.assertion(job != null, "No job found . Call from " + getClass().getName());

        LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1,"In BulkUpdateFP selected application count : ", applications != null ? applications.size() : 0 , " of job ", job);

        if(job.getAppWorkFlowStage()!= null && job.getAppWorkFlowStage().getStageType()== StageType.SUCCESSFUL 
                && job.getNoOfCandidatesApplied() > job.getMaxShortlistApplicants() && applications != null)
        {
            Filter<JobApplication>  filter              =   JobApplication.SearchByStageType().byStageTypesIn(CollectionUtils.createSet(StageType.INTERVIEW));
            Collection              alreadyShortlisted  =   CollectionFilter.filter(applications, filter);
            int                     totalShortlisted    =   applications.size() - alreadyShortlisted.size() + job.getNoOfCandidatesFor(job.getWorkFlowByStageType(StageType.SUCCESSFUL));
          
            BusinessObjectParser.assertFieldCondition(totalShortlisted <= job.getMaxShortlistApplicants() , job , Job.MULTIPLEREFERENCE_JobApplications, "exceedMaxShortlisted");
        }
        
        if(job.getAppWorkFlowStage() != null)
        {
            for(JobApplication application : applications)
            {
                application.setWorkFlowStage(job.getAppWorkFlowStage());

                LogMgr.log(JobApplication.LOG, LogLevel.PROCESSING1,"In BulkUpdateFP Job Application Status successfully changed : ", application );
            }
        }      
                
        return super.processForm(process, submission, params);
    }
}