package com.spring.infra.quartz;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.springframework.stereotype.Service;

import com.spring.infra.batch.BatchJobInfoData;
import com.spring.infra.batch.BatchJobInfoService;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class QuartzScheduleService {
    
    private final Scheduler scheduler;
    private final BatchJobInfoService batchJobInfoService;

    public void clearJobs() {
        try {
            scheduler.clear();
        } catch (SchedulerException e) {
            throw new IllegalStateException();
        }
    }

    public void createJobTrigger(String beanName) {
        BatchJobInfoData batchJobInfoData = batchJobInfoService.getBatchJobInfo(beanName);

        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("jobName", batchJobInfoData.getJobName());

        JobDetail jobDetail = JobBuilder.newJob(QuartzJobLauncher.class)
                .withIdentity(batchJobInfoData.getJobName(), batchJobInfoData.getJobGroup())
                .setJobData(jobDataMap)
                .storeDurably(true)
                .withDescription(batchJobInfoData.getDescription())
                .build();

        CronTrigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(batchJobInfoData.getJobName() + "Trigger", batchJobInfoData.getJobGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(batchJobInfoData.getCronExpression()))
                .withDescription(batchJobInfoData.getDescription())
                .build();

        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            throw new IllegalStateException("Error scheduling Quartz job: " + batchJobInfoData.getJobName(), e);
        }
    }

}
