package com.axelor.apps.hr.job;

import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.service.DailyReportServiceImpl;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import java.util.List;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.quartz.SchedulerException;

/** An example {@link Job} class that prints a some messages to the stderr. */
public class CalculateAttendanceJob implements Job {

  private final Logger log = LoggerFactory.getLogger(CalculateAttendanceJob.class);

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException{

    if (isRunning(context)) {
      return;
    }

    try {
      List<DailyReport> dailyReportList =
          Beans.get(DailyReportRepository.class)
              .all()
              .filter("self.isCalculated = ?", false)
              .fetch();

      if (!dailyReportList.isEmpty()) {
        Beans.get(DailyReportServiceImpl.class).workingHoursForAll(dailyReportList);
        log.debug("Working hours calculated successfully.");
      } else {
        log.debug("No new records to process.");
      }

    } catch (Exception e) {
      log.error("An error occurred while calculating working hours.");
      TraceBackService.trace(e);
    }
  }

  private boolean isRunning(JobExecutionContext context) {
    try {
      return context
          .getScheduler()
          .getCurrentlyExecutingJobs()
          .stream()
          .anyMatch(
              j ->
                  j.getTrigger().equals(context.getTrigger())
                      && !j.getFireInstanceId().equals(context.getFireInstanceId()));
    } catch (SchedulerException e) {
      return false;
    }
  }

}
