package xyz.wbsite.dbtool.web.frame.schedule;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.util.ErrorHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Scheduler extends ThreadPoolTaskScheduler implements ErrorHandler {

    private Map<String, TaskWrapper> taskMap = new HashMap<>();

    public Scheduler() {
        setErrorHandler(this);
        setPoolSize(4);
        initialize();
    }

    public boolean createOrRepeat(RunTask task) {
        if (taskMap.containsKey(task.taskId())) {
            ScheduledFuture<?> scheduledFuture = taskMap.get(task.taskId()).future;
            scheduledFuture.cancel(false);
        }
        taskMap.put(task.taskId(), new TaskWrapper(task));
        return true;
    }

    public boolean remove(String taskId) {
        if (taskMap.containsKey(taskId)) {
            ScheduledFuture<?> scheduledFuture = taskMap.get(taskId).future;
            scheduledFuture.cancel(false);
            taskMap.remove(taskId);
        }
        return true;
    }

    public boolean start(String taskId) {
        if (taskMap.containsKey(taskId)) {
            taskMap.get(taskId).run = true;
            taskMap.get(taskId).future = taskMap.get(taskId).target.schedule(this);
            return true;
        }
        return false;
    }

    public boolean stop(String taskId) {
        if (taskMap.containsKey(taskId)) {
            taskMap.get(taskId).run = false;
            ScheduledFuture<?> scheduledFuture = taskMap.get(taskId).future;
            scheduledFuture.cancel(false);
            return true;
        }
        return false;
    }

    @Override
    public void handleError(Throwable throwable) {
        String message = throwable.getMessage();
        Pattern compile = Pattern.compile("(\\[.*])执行异常！任务ID(\\(.*\\))");
        Matcher matcher = compile.matcher(message);
        if (matcher.find()) {

        }
    }

    class TaskWrapper {
        RunTask target;
        String taskId;
        String taskName;
        String taskNote;
        boolean run;
        ScheduledFuture<?> future;

        public TaskWrapper(RunTask runTask) {
            this.target = runTask;
            this.taskId = runTask.taskId();
            this.taskName = runTask.taskName();
            this.taskNote = runTask.taskNote();
            this.future = runTask.schedule(Scheduler.this);
            this.run = true;
        }
    }
}