package com.yonge.cooleshow.task.core;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yonge.cooleshow.task.core.TaskStatus;
import com.yonge.cooleshow.task.dal.model.Task;
import com.yonge.cooleshow.task.service.TaskService;

public class DelegatingJob implements Job {

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

	private Job job;

	TaskService taskService;

	public DelegatingJob(Job job, TaskService taskService) {
		this.job = job;
		this.taskService = taskService;
	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobKey jobKey = context.getJobDetail().getKey();
		String group = jobKey.getGroup();
		String name = jobKey.getName();

		Task task = taskService.queryTask(name, group);
		if (task == null) {
			return;
		}
		if (task.getStatus() == TaskStatus.EXECUTING.getCode()) {
			LOGGER.warn("Failed to execute,because the Job[{}.{}] status is {}", group, name, TaskStatus.EXECUTING);
			return;
		} else if (task.getStatus() == TaskStatus.PAUSED.getCode()) {
			LOGGER.warn("Failed to execute,because the Job[{}.{}] status is {}", group, name, TaskStatus.PAUSED);
			return;
		}
		taskService.updateTaskStatus(task.getId(), TaskStatus.getTaskStatus(task.getStatus()), TaskStatus.EXECUTING);
		try {
			job.execute(context);
		} catch (Exception e) {
			throw new RuntimeException("执行任务出错", e);
		} finally {
			taskService.updateTaskStatus(task.getId(), TaskStatus.EXECUTING, TaskStatus.EXECUTED);
		}
	}

}
