package com.capgemini.reports.execution.posting;

import com.capgemini.reports.execution.AbstractExecutionReport;
import com.capgemini.reports.quartz.SchedulerServer;
import com.capgemini.reports.quartz.jobs.ScheduledJob;
import lombok.AllArgsConstructor;
import org.quartz.*;

/** Class representing the strategy to post a scheduling template into Quartz DB. */
@AllArgsConstructor
public class SchedulingPostingStrategy implements IPostingStrategy {

    private final SchedulerServer schedulingServer;
    private final Trigger trigger;

    @Override
    public void handleRequest(final AbstractExecutionReport<?, ?> template) throws SchedulerException {
        JobDetail job = getScheduledJobDetail(template, trigger.getJobKey());

        // Push the job to Quartz
        try {
            schedulingServer.schedule(job, trigger);
        } catch (SchedulerException e) {
            throw new SchedulerException("Unable to schedule the job associated to the template " + template.getReportIdentifier().getReportName() + " " + template.getReportTechnicalUid(), e);
        }
    }

    /**
     * Return the needed {@link JobDetail} for a delayed execution of report.
     * 
     * @param report {@link AbstractExecutionReport} - the implementation of the report
     * @param jobKey {@link JobKey} - the JobKey used for the scheduling
     * @return the JobDetail
     */
    public static JobDetail getScheduledJobDetail(final AbstractExecutionReport<?, ?> report, final JobKey jobKey) {
        // Begin setting up the JobBuilder
        JobBuilder jobBuilder = JobBuilder.newJob(ScheduledJob.class).withIdentity(jobKey.getName(), jobKey.getGroup());
        // The method requestRecovery asks the scheduler to re-execute this job
        jobBuilder.requestRecovery();
        // Add kurt data
        ScheduledJob.prepareData(jobBuilder, report.getSchedulingId(), report.getReportBuilderClassName());
        // Build the job
        return jobBuilder.build();
    }

}
