package com.njzscloud.common.core.thread;

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

@SuppressWarnings("unchecked")
public class ThreadContext {
    private static final Map<Thread, Map<String, Object>> CONTEXT_CACHE = new ConcurrentHashMap<>();

    /**
     * 获取
     *
     * @param key          键
     * @param defaultValue 默认值
     */
    public static <T> T get(String key, T defaultValue) {
        return (T) CONTEXT_CACHE
            .computeIfAbsent(Thread.currentThread(), k -> new ConcurrentHashMap<>())
            .computeIfAbsent(key, k -> defaultValue);
    }

    /**
     * 获取
     *
     * @param key 键
     */
    public static <T> T get(String key) {
        return (T) CONTEXT_CACHE
            .computeIfAbsent(Thread.currentThread(), k -> new ConcurrentHashMap<>())
            .get(key);
    }

    /**
     * 保存
     *
     * @param key   键
     * @param value 值
     */
    public static <T> T set(String key, T value) {
        return (T) CONTEXT_CACHE
            .computeIfAbsent(Thread.currentThread(), k -> new ConcurrentHashMap<>())
            .put(key, value);
    }

    /**
     * 移除
     *
     * @param key 键
     */
    public static void remove(String key) {
        CONTEXT_CACHE
            .computeIfAbsent(Thread.currentThread(), k -> new ConcurrentHashMap<>())
            .remove(key);
    }

    /**
     * 清理当前线程对应的数据
     */
    public static void clear() {
        CONTEXT_CACHE.remove(Thread.currentThread());
    }

}
