package com.pwt.netty.conponents;

import io.netty.channel.Channel;
import org.springframework.stereotype.Component;

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

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

    private static Map<String, Channel> channelCache = new ConcurrentHashMap<String, Channel>();

    public static void put(String key, Channel value) {
        channelCache.put(key, value);
    }

    public static Channel get(String key) {
        return channelCache.get(key);
    }

    public static void remove(String key) {
        channelCache.remove(key);
    }

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

    public static Set<String> keySet()
    {
        return channelCache.keySet();
    }

    public static boolean containsKey(String key)
    {
        return channelCache.containsKey(key);
    }

    public static boolean containsValue(Channel channel)
    {
        return channelCache.containsValue(channel);
    }

    public static String getChannelClientId(Channel channel)
    {
        String key = null;
        Optional<Map.Entry<String, Channel>> optional = channelCache.entrySet().stream().filter(v -> v.getValue() == channel).findFirst();
        if (optional.isPresent())
        {
            key = optional.get().getKey();
        }
        return key;
    }
}
