package com.qmth.teachcloud.mark.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> omrTaskMap = new HashMap<>();
    private static final Map<String, TaskLock> inspectedStudentMap = new HashMap<>();

    public static Map<String, TaskLock> getFormalTaskMap(){
        return formalTaskMap;
    }


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

    public static TaskLock getOmrTask(String key) {
        TaskLock taskLock = omrTaskMap.get(key);
        if (taskLock == null) {
            synchronized (omrTaskMap) {
                taskLock = omrTaskMap.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;
    }
}
