package cn.com.qmth.stmms.biz.utils;

import java.util.HashMap;
import java.util.Map;

public class TaskLockUtil {

    // 评卷任务并发处理互斥锁
    private static final Map<String, TaskLock> formalTaskMap = new HashMap<>();

    // 试评任务并发处理互斥锁
    private static final Map<String, TaskLock> trialTaskMap = new HashMap<>();

    // 复核整卷并发处理互斥锁
    private static final Map<String, TaskLock> inspectedStudentMap = new HashMap<>();

    // 复核评卷任务并发处理互斥锁
    private static final Map<String, TaskLock> inspectedLibraryMap = new HashMap<>();

    public static void clearTimeoutTask(long timeoutMinute) {
        for (TaskLock taskLock : trialTaskMap.values()) {
            taskLock.expire(timeoutMinute);
        }
        for (TaskLock taskLock : formalTaskMap.values()) {
            taskLock.expire(timeoutMinute);
        }
        for (TaskLock taskLock : inspectedStudentMap.values()) {
            taskLock.expire(timeoutMinute);
        }
        for (TaskLock taskLock : inspectedLibraryMap.values()) {
            taskLock.expire(timeoutMinute);
        }
    }

    public static TaskLock getTrialTask(String key) {
        TaskLock taskLock = trialTaskMap.get(key);
        if (taskLock == null) {
            synchronized (trialTaskMap) {
                taskLock = trialTaskMap.computeIfAbsent(key, k -> new TaskLock());
            }
        }
        return taskLock;
    }

    public static TaskLock getFormalTask(String key) {
        TaskLock taskLock = formalTaskMap.get(key);
        if (taskLock == null) {
            synchronized (formalTaskMap) {
                taskLock = formalTaskMap.computeIfAbsent(key, k -> new TaskLock());
            }
        }
        return taskLock;
    }

    public static TaskLock getInspectedStudentTask(String key) {
        TaskLock taskLock = inspectedStudentMap.get(key);
        if (taskLock == null) {
            synchronized (inspectedStudentMap) {
                taskLock = inspectedStudentMap.computeIfAbsent(key, k -> new TaskLock());
            }
        }
        return taskLock;
    }

    public static TaskLock getInspectedLibraryTask(String key) {
        TaskLock taskLock = inspectedLibraryMap.get(key);
        if (taskLock == null) {
            synchronized (inspectedLibraryMap) {
                taskLock = inspectedLibraryMap.computeIfAbsent(key, k -> new TaskLock());
            }
        }
        return taskLock;
    }

}
