package com.spring.domain.schedule.service;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.stereotype.Service;

import com.spring.domain.schedule.dto.ReScheduleJobRequest;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class ReScheduleJobService {
    
    private final Scheduler scheduler;

    public boolean rescheduleJob(ReScheduleJobRequest request) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(request.getJobName() + "Trigger", request.getJobGroup());
            Trigger oldTrigger = scheduler.getTrigger(triggerKey);
            if (oldTrigger != null) {
                CronTrigger newTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(oldTrigger.getKey())
                    .withDescription(oldTrigger.getDescription())
                    .withPriority(oldTrigger.getPriority())
                    .forJob(oldTrigger.getJobKey())
                    .withSchedule(CronScheduleBuilder.cronSchedule(request.getCronExpression().trim())
                    .withMisfireHandlingInstructionDoNothing())
                    .build();
                scheduler.rescheduleJob(oldTrigger.getKey(), newTrigger);
                return true;
            }
            return false;
        } catch (SchedulerException e) {
            return false;
        }
    }

}
