package com.dxhy.common.utils;

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

import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.util.StringHelper;

/**
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:57:19
 *
 */

@SuppressWarnings({"AlibabaLowerCamelCaseVariableNaming", "AlibabaCollectionInitShouldAssignCapacity"})
public class BaseContextHandler {
    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static String getUserID() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_ID);
        return returnObjectValue(value);
    }

    public static String getUsername() {
        Object value = get(CommonConstants.CONTEXT_KEY_USERNAME);
        return returnObjectValue(value);
    }

    public static String getLonginname() {
        Object value = get(CommonConstants.CONTEXT_KEY_LOGINNAME);
        return returnObjectValue(value);
    }

    public static String getUserInfo() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER);
        return returnObjectValue(value);
    }

    public static String getName() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_NAME);
        return StringHelper.getObjectValue(value);
    }

    public static String getToken() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_TOKEN);
        return StringHelper.getObjectValue(value);
    }

    public static void setToken(String token) {
        set(CommonConstants.CONTEXT_KEY_USER_TOKEN, token);
    }

    public static void setName(String name) {
        set(CommonConstants.CONTEXT_KEY_USER_NAME, name);
    }

    public static void setUserID(String userID) {
        set(CommonConstants.CONTEXT_KEY_USER_ID, userID);
    }

    public static void setUsername(String username) {
        set(CommonConstants.CONTEXT_KEY_USERNAME, username);
    }

    public static void setLoginname(String loginname) {
        set(CommonConstants.CONTEXT_KEY_LOGINNAME, loginname);
    }

    public static void setUserInfo(String userInfo) {
        set(CommonConstants.CONTEXT_KEY_USER, userInfo);
    }

    private static String returnObjectValue(Object value) {
        return value == null ? null : value.toString();
    }

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

}
