package com.pwt.netty.conponents;

import io.netty.channel.socket.SocketChannel;

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

/**
 * @author linyun
 * @version V1.0
 * @Title: WebSocketChannelRepository
 * @Description: webSocke通道管理工具
 * @date 2022/11/11
 **/
public class WebSocketChannelRepository {

    private static Map<String, SocketChannel> channelMap = new ConcurrentHashMap<>();

    public static void put(String clientId, SocketChannel channel){
        channelMap.put(clientId, channel);
    }

    public static Map<String, SocketChannel> getChannels(){
        return channelMap;
    }

    public static SocketChannel get(String clientId){
        return channelMap.get(clientId);
    }

    public static void remove(String clientId){
        channelMap.remove(clientId);
    }

    public static int size(){
        return channelMap.size();
    }

    public static boolean containsKey(String clientId)
    {
        return channelMap.containsKey(clientId);
    }

    public static boolean containsValue(SocketChannel channel)
    {
        return channelMap.containsValue(channel);
    }

    public static String getChannelClientId(SocketChannel channel)
    {
        String clientId = null;
        Optional<Map.Entry<String, SocketChannel>> optional = getChannels().entrySet().stream().filter(k -> k.getValue().equals(channel)).findFirst();
        if (optional.isPresent())
        {
            clientId = optional.get().getKey();
        }
        return clientId;
    }
}
