package com.spring.domain.schedule.service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.stereotype.Service;

import com.spring.common.error.BizBaseException;
import com.spring.domain.schedule.dto.RecentJobResponse;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class DashBoardJobService {

    private final Scheduler scheduler;

    public List<RecentJobResponse> getRecentJobs() {
        List<RecentJobResponse> recentJobs = new ArrayList<>();
        try {
            for (String groupName : scheduler.getJobGroupNames()) {
                for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(groupName))) {
                    List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                    for (Trigger trigger : triggers) {
                        recentJobs.add(new RecentJobResponse(
                            jobKey.getName(),
                            jobKey.getGroup(),
                            trigger.getPreviousFireTime() != null ? trigger.getPreviousFireTime().getTime() : null,
                            scheduler.getTriggerState(trigger.getKey()).name()
                        ));
                    }
                }
            }
        } catch (SchedulerException e) {
            throw new BizBaseException();
        }
        return recentJobs.stream()
                .filter(job -> job.getFiredTime() != null)
                .sorted((j1, j2) -> Long.compare(j2.getFiredTime(), j1.getFiredTime()))
                .limit(10)
                .collect(Collectors.toList());
    }
    
}
