package performa.batch;

import java.util.Set;
import oneit.appservices.batch.ORMBatch;
import oneit.logging.*;
import oneit.objstore.ObjectTransaction;
import oneit.objstore.StorageException;
import oneit.objstore.rdbms.filters.LessThanFilter;
import oneit.utils.DateDiff;
import oneit.utils.parsers.FieldException;
import performa.intercom.utils.IntercomUtils;
import performa.orm.Job;
import performa.orm.Company;
import performa.orm.types.JobStatus;


public class CloseJobBatch  extends ORMBatch
{
    public static LoggingArea CLOSE_JOB_BATCH = LoggingArea.createLoggingArea("CloseJobBatch");

    @Override
    public void run(ObjectTransaction ot) throws StorageException, FieldException
    {
        LogMgr.log (CLOSE_JOB_BATCH, LogLevel.PROCESSING1, "RUNNING Close Job Batch");

        Job[]   expiringJobs    = Job.SearchByAll()
                                        .andApplyBy(new LessThanFilter<>(DateDiff.getToday()))
                                        .search(ot);
        
        for (Job job : expiringJobs)
        {
            job.setJobStatus(JobStatus.COMPLETE);
            job.setIsManuallyClosed(Boolean.FALSE);
            
            LogMgr.log(CLOSE_JOB_BATCH, LogLevel.PROCESSING1, "Setting Job Status to Closed in job : ", job);
        }
        
        // Update closed job details to intercom
        Set<Company>    companies   =   Job.pipesJob(expiringJobs).toCreatedBy().toCompany().uniqueVals();
        
        for (Company company : companies)
        {
            IntercomUtils.updateCompany(company);
        }
    }
}