package com.yida.data.websocket.util;

import cn.hutool.core.util.StrUtil;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;

/**
 * websocket连接管理
 */
@Slf4j
public class SessionManager {

    private final static ConcurrentHashMap<Long, String> USER_TOKEN = new ConcurrentHashMap<>();
    private final static ConcurrentHashMap<String, Long> TOKEN_USER = new ConcurrentHashMap<>();

    public static void add(Long userId, String token) {
        USER_TOKEN.put(userId, token);
        TOKEN_USER.put(token, userId);
    }

    public static void del(Long userId) {
        String token = USER_TOKEN.get(userId);
        if (StrUtil.isNotBlank(token)) {
            USER_TOKEN.remove(userId);
            TOKEN_USER.remove(token);
        }
    }

    public static void del(String token) {
        Long userId = TOKEN_USER.get(token);
        if (userId != null) {
            USER_TOKEN.remove(userId);
            TOKEN_USER.remove(token);
        }
    }

    public static Boolean exist(Long userId) {
        String token = USER_TOKEN.get(userId);
        return USER_TOKEN.containsKey(userId) && TOKEN_USER.containsKey(token);
    }

    public static Boolean exist(String token) {
        Long userId = TOKEN_USER.get(token);
        return USER_TOKEN.containsKey(userId) && TOKEN_USER.containsKey(token);
    }
}
