package com.inspect.base.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.inspect.base.core.constant.SecurityConstants;
import com.inspect.base.core.text.Convert;
import com.inspect.base.core.utils.StringUtils;

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

public class SecurityContextHolder {
    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? "" : value);
    }

    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, ""));
    }

    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        return StringUtils.cast(map.getOrDefault(key, null));
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = (Map) THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap();
            THREAD_LOCAL.set(map);
        }

        return (Map) map;
    }

    public static void setLocalMap(Map<String, Object> threadLocalMap) {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static Long getUserId() {
        return Convert.toLong(get("user_id"), 1L);
    }

    public static void setUserId(String account) {
        set("user_id", account);
    }

    public static String getUserName() {
        return get("username");
    }

    public static void setUserName(String username) {
        set("username", username);
    }

    public static String getUserKey() {
        return get(SecurityConstants.USER_KEY);
    }

    public static void setUserKey(String userKey) {
        set(SecurityConstants.USER_KEY, userKey);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }
}
