package com.dingtalk.h5app.quickstart.service.impl;

import com.dingtalk.h5app.quickstart.mapper.CronMapper;
import com.dingtalk.h5app.quickstart.quartz.MyJob;
import com.dingtalk.h5app.quickstart.service.QuartzService;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

/**
 * @author Shawn
 */
@Service
public class QuartzServiceImpl implements QuartzService {

    @Autowired
    private CronMapper cronMapper;

    @Autowired
    Scheduler scheduler;

    @Override
    public String insertQuartz(String userid, String cron,String token,String frequency) throws SchedulerException,SQLException {


            if (cronMapper.addCron(userid + cron, cron, userid,frequency) == 1){
                JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                        .withIdentity(JobKey.jobKey(userid + cron,userid))
                        .usingJobData("userid",userid)
                        .usingJobData("frequency",frequency)
                        .usingJobData("token",token)
                        .build();
                System.out.println("jobName:*"+userid + cron+"*");
                System.out.println("group:*"+userid+"*");
                Trigger trigger = TriggerBuilder.newTrigger().withIdentity(TriggerKey.triggerKey(userid + cron,userid))
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();

                scheduler.scheduleJob(jobDetail,trigger);
                scheduler.start();
                return "success";
            }else {
                return "error";
            }

    }
}
