package com.base.task.core;

import com.base.task.model.Enums.TaskTypeEnum;
import com.base.task.model.Task;
import com.base.task.model.TaskPreparations;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

public class TaskCache {

    private static TaskCache taskCache = new TaskCache();

    private TaskCache(){}

    public static TaskCache getInstance(){
        return taskCache;
    }

    /**
     * 任务可执行文件路径
     */
    private Map<TaskTypeEnum, String> taskExePathMap = new HashMap<>();

    private Map<TaskTypeEnum, String> taskOkFileResult = new ConcurrentHashMap<>();

    /**
     * 任务队列
     */
    private LinkedBlockingQueue<Task> tasks = new LinkedBlockingQueue<>();

    private Map<TaskTypeEnum, List<Task>> currentTaskMap  = new ConcurrentHashMap<>();

    public LinkedBlockingQueue<Task> getTasks(){
        return tasks;
    }

    public synchronized boolean addTask(Task task){
        return tasks.add(task);
    }

    public synchronized boolean removeTask(String taskSerial){
        return tasks.remove(new Task(taskSerial));
    }

    public synchronized Task peekTask(){
        return tasks.peek();
    }

    public int getQueueTaskNumber(){
        return tasks.size();
    }

    public int getTypeCurrentNum(TaskTypeEnum taskTypeEnum){
        if (currentTaskMap.get(taskTypeEnum) == null){
            return 0;
        }
        return currentTaskMap.get(taskTypeEnum).size();
    }

    public void addCurrentTask(Task task){
        currentTaskMap.computeIfAbsent(task.getTaskType(), k -> new ArrayList<>());
        currentTaskMap.get(task.getTaskType()).add(task);
    }

    public synchronized void removeCurrentTask(Task task){
        currentTaskMap.computeIfAbsent(task.getTaskType(), k -> new ArrayList<>());
        currentTaskMap.get(task.getTaskType()).remove(task);
        System.out.println(currentTaskMap);
    }

    public Map<TaskTypeEnum, List<Task>> getCurrentTaskMap(){
        return currentTaskMap;
    }

    public void initCurrentTaskMap(TaskPreparations taskPreparations){
        TaskTypeEnum[] taskTypeEnums = TaskTypeEnum.values();
        for (TaskTypeEnum taskTypeEnum:taskTypeEnums){
            int j = 0 ;
            while(j<taskPreparations.getExePackageCounts()) {
                currentTaskMap.put(taskTypeEnum,new ArrayList<>());
                j++;
            }
        }
    }
}