package com.m2pool.common.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.m2pool.common.core.constant.OpenApiKeyConstants;
import com.m2pool.common.core.text.Convert;
import com.m2pool.common.core.utils.StringUtils;

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

/**
* @Description 获取当前线程变量中的 用户id、用户名称、Token等信息
* @Date 2024/6/12 11:32
* @Author dy
*/
public class OpenApiContextHolder
{
   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 ? StringUtils.EMPTY : value);
   }

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

   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 = THREAD_LOCAL.get();
       if (map == null)
       {
           map = new ConcurrentHashMap<String, Object>();
           THREAD_LOCAL.set(map);
       }
       return map;
   }

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

   public static String getApiUser()
   {
       return get(OpenApiKeyConstants.API_USER);
   }

   public static void setApiUser(String user)
   {
       set(OpenApiKeyConstants.API_USER, user);
   }

   public static String getApiIp()
   {
       return get(OpenApiKeyConstants.API_IP);
   }

   public static void setApiIp(String ip)
   {
       set(OpenApiKeyConstants.API_IP, ip);
   }

   public static String getApiKey()
   {
       return get(OpenApiKeyConstants.API_KEY);
   }

   public static void setApiKey(String apiKey)
   {
       set(OpenApiKeyConstants.API_KEY, apiKey);
   }

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