package cn.com.taiji.track.config;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.AttributeKey;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.concurrent.ConcurrentHashMap;


public class NettyConfig {

    /**
     * 定义一个channel组，管理所有的channel
     */
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    /**
     * 存放用户与Chanel的对应信息，用于给指定用户发送消息
     */
    private static ConcurrentHashMap<String, Object> userChannelMap = new ConcurrentHashMap<>();

    private NettyConfig() {}

    /**
     * 获取channel组
     * @return
     */
    public static ChannelGroup getChannelGroup() {
        return channelGroup;
    }

    /**
     * 判断一个通道是否有用户在使用
     * 可做信息转发时判断该通道是否合法
     * @param channel
     * @return
     */
    public static boolean hasUser(Channel channel) {
        AttributeKey<String> key = AttributeKey.valueOf("user");
        return (channel.hasAttr(key) || channel.attr(key).get() != null);
    }


    /**
     * 根据用户id获取该用户的通道
     * @param userId
     * @return
     */
    public static Object getChannelByUserId(String userId) {
        return userChannelMap.get(userId);
    }

    /**
     * 判断一个用户是否在线
     * @param userId
     * @return
     */
    public static Boolean online(String userId) {
        return userChannelMap.containsKey(userId) && userChannelMap.get(userId) != null;
    }

    /**
     * 获取用户channel map
     * @return
     */
    public static ConcurrentHashMap<String, Object> getUserChannelMap(){
        return userChannelMap;
    }
}
