package com.tofly.common.schedulle.config;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author tuonbed
 * @date 2020/3/26  14:19
 */
@Component
public class MyTaskRegistrar implements DisposableBean {


    private final Map<Runnable, MyScheduleTask> scheduledTasks = new ConcurrentHashMap<>(16);

    @Autowired
    private TaskScheduler taskScheduler;

    public TaskScheduler getScheduler() {
        return this.taskScheduler;
    }

    /**
     * 新增定时任务
     * @param task
     * @param cronExpression
     */
    public void addCronTask(Runnable task, String cronExpression) {
        addCronTask(new CronTask(task, cronExpression));
    }

    public void addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {
                removeCronTask(task);
            }

            this.scheduledTasks.put(task, scheduleCronTask(cronTask));
        }
    }

    public void updateCronTask(CronTask cronTask, String cronExpression) {
        if (cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {
                removeCronTask(task);
            }
            this.scheduledTasks.put(task, scheduleCronTask(new CronTask(task,cronExpression)));
        }
    }

    public Map<Runnable, MyScheduleTask> getScheduledTasks(){
        return scheduledTasks;
    }

    /**
     * 移除定时任务
     * @param task
     */
    public void removeCronTask(Runnable task) {
        MyScheduleTask myScheduleTask = this.scheduledTasks.remove(task);
        if (myScheduleTask != null){
            myScheduleTask.cancel();
        }

    }

    public MyScheduleTask scheduleCronTask(CronTask cronTask) {
        MyScheduleTask myScheduleTask = new MyScheduleTask();
        myScheduleTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());

        return myScheduleTask;
    }


    @Override
    public void destroy() {
        for (MyScheduleTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }
}
