package com.ssj.quartz.service.impl;

import com.ssj.quartz.dao.JobEntityDao;
import com.ssj.quartz.domian.JobEntity;
import com.ssj.quartz.service.JobEntityService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class JobEntityServiceImpl implements JobEntityService{
	@Autowired
    private JobEntityDao dao;
	
	@Override
	public JobEntity getJobEntityById(Integer id) {
		return dao.getById(id);
	}

	@Override
	public List<JobEntity> loadJobs() {
		return dao.findAll();
	}

	@Override
	public JobDataMap getJobDataMap(JobEntity job) {
		JobDataMap map = new JobDataMap();
		map.put("jobClassName", job.getJobClassName());
		map.put("name", job.getName());
		map.put("group", job.getGroup());
		map.put("cronExpression", job.getCron());
		map.put("parameter", job.getParameter());
		map.put("JobDescription", job.getDescription());
		map.put("vmParam", job.getVmParam());
		map.put("jarPath", job.getJarPath());
		map.put("status", job.getStatus());
		return map;
	}

	@Override
	public JobDetail geJobDetail(JobKey jobKey, String description,
			JobDataMap map) throws ClassNotFoundException {
		String jobClassName=map.getString("jobClassName");
		Class taskClass = Class.forName(jobClassName);
		return JobBuilder.newJob(taskClass)
	                .withIdentity(jobKey)
	                .withDescription(description)
	                .setJobData(map)
	                .storeDurably()
	                .build();
	}

	@Override
	public Trigger getTrigger(JobEntity job) {
		return TriggerBuilder.newTrigger()
                .withIdentity(job.getName(), job.getGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(job.getCron()))
                .build();
	}

	@Override
	public JobKey getJobKey(JobEntity job) {
		return JobKey.jobKey(job.getName(), job.getGroup());
	}

}
