package com.ym.mec.task.core;

import java.util.List;

import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.ym.mec.task.dal.model.Task;
import com.ym.mec.task.service.TaskService;

@Configuration
public class TaskSchedulerBootstrap implements InitializingBean {

	private static final Logger LOGGER = LoggerFactory.getLogger(TaskSchedulerBootstrap.class);

	@Autowired
	private TaskService taskService;

	@Autowired
	private LocalSchedulerFactoryBean localSchedulerFactoryBean;

	@SuppressWarnings("unchecked")
	@Override
	public void afterPropertiesSet() throws Exception {

		Scheduler scheduler = localSchedulerFactoryBean.getScheduler();
		if (scheduler == null) {
			throw new IllegalArgumentException("[TaskSchedulerBootstrap]在实例化过程中，参数[scheduler]没有被设置，请检查配置");
		}
		if (taskService == null) {
			throw new IllegalArgumentException("[TaskSchedulerBootstrap]在实例化过程中，参数[taskService]没有被设置，请检查配置");
		}
		List<Task> tasks = taskService.queryTasks();
		Class<?> clazz = null;
		for (Task task : tasks) {
			clazz = Class.forName(task.getJobClass());
			if (BaseTask.class.isAssignableFrom(clazz)) {
				QuartzHelper.addJob(scheduler, task.getName(), task.getGroup(), task.getName(), task.getGroup(),
						(Class<? extends BaseTask>) Class.forName(task.getJobClass()), task.getTimeExp());
				LOGGER.info("Successed add job[{}.{}] to Schedule", task.getGroup(), task.getName());
			} else {
				LOGGER.warn("Failed add job[{}.{}],because class[{}] not implements com.yqh.p2p.task.BaseTask", task.getGroup(), task.getName(),
						task.getJobClass());
			}
		}
	}

}
