package com.yonge.cooleshow.task.service.impl;

import java.util.List;
import java.util.Map;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonge.cooleshow.task.core.QuartzHelper;
import com.yonge.cooleshow.task.core.TaskException;
import com.yonge.cooleshow.task.core.TaskStatus;
import com.yonge.cooleshow.task.dal.dao.TaskDao;
import com.yonge.cooleshow.task.dal.model.Task;
import com.yonge.cooleshow.task.service.TaskService;

@Service
public class TaskServiceImpl implements TaskService {

	@Autowired
	private TaskDao taskDao;

	@Override
	public List<Task> queryTasks() {
		return taskDao.queryAvailableTasks();
	}

	@Override
	public List<Task> queryPage(Map<String, Object> params) {
		return taskDao.queryPage(params);
	}

	@Override
	public int queryCount(Map<String, Object> params) {
		return taskDao.queryCount(params);
	}

	@Override
	public Task queryTask(Long taskId) {
		return taskDao.get(taskId);
	}

	@Override
	public Task queryTask(String jobName, String groupName) {
		return taskDao.queryTaskByNameAndGroup(jobName, groupName);
	}

	@Override
	public boolean updateTaskStatus(Long taskId, TaskStatus oldStatus, TaskStatus curStatus) {
		return taskDao.updateStatusById(taskId, oldStatus.getCode(), curStatus.getCode()) > 0;
	}

	@Override
	public boolean execute(Long taskId, Scheduler scheduler) throws SchedulerException {
		Task task = taskDao.getLocked(taskId);
		if (task == null) {
			throw new TaskException("任务编号[{" + taskId + "}]不存在");
		}
		if (task.getStatus() == TaskStatus.EXECUTING.getCode() || task.getStatus() == TaskStatus.PAUSED.getCode()) {
			throw new TaskException("“执行中”或“暂停”状态的任务不能被执行");
		}
		return QuartzHelper.triggerJob(scheduler, task.getName(), task.getGroup());
	}

	@Override
	public boolean pause(Long taskId, Scheduler scheduler) throws SchedulerException {
		Task task = taskDao.getLocked(taskId);
		if (task == null) {
			throw new TaskException("任务编号[{" + taskId + "}]不存在");
		}
		if (task.getStatus() == TaskStatus.EXECUTING.getCode() || task.getStatus() == TaskStatus.PAUSED.getCode()) {
			throw new TaskException("“执行中”或“暂停”状态的任务不能被暂停执行");
		}
		if (QuartzHelper.pauseJob(scheduler, task.getName(), task.getGroup())) {
			return taskDao.updateStatusById(taskId, task.getStatus(), TaskStatus.PAUSED.getCode()) > 0;
		}
		return false;
	}

	@Override
	public boolean resume(Long taskId, Scheduler scheduler) throws SchedulerException {
		Task task = taskDao.getLocked(taskId);
		if (task == null) {
			throw new TaskException("任务编号[{" + taskId + "}]不存在");
		}
		if (task.getStatus() != TaskStatus.PAUSED.getCode()) {
			throw new TaskException("只有“暂停”状态的任务才能被恢复执行");
		}
		if (QuartzHelper.resumeJob(scheduler, task.getName(), task.getGroup())) {
			return taskDao.updateStatusById(taskId, task.getStatus(), TaskStatus.READY.getCode()) > 0;
		}
		return false;
	}

}
