package com.artfess.base.webSocket;

import com.artfess.base.conf.NettyConfig;
import com.artfess.base.util.BeanUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author 陈实
 * @Package com.artfess.base.webSocket
 * @date 2021/9/16 10:45
 * @Description:
 */
@Service
@Slf4j
public class PushServiceImpl implements PushService{

    @Override
    public void pushMsgToAccount(String account, String msg){
        ConcurrentHashMap<String, Set<ChannelId>> userChannelMap = NettyConfig.getUserChanIdMap();
        Set<ChannelId> channelSet = userChannelMap.get(account);
        // 如果该用户的客户端是与本服务器建立的channel,直接推送消息
        if(BeanUtils.isNotEmpty(channelSet)){
            for(ChannelId chanId : channelSet){
                Channel userChannel = NettyConfig.getChannelGroup().find(chanId);
                if (userChannel != null) {
                    userChannel.writeAndFlush(new TextWebSocketFrame(msg));
                }
            }
        }
    }

    @Override
    public void pushMsgToAll(String msg){
        log.info("【Websocket】广播消息:"+msg);
        NettyConfig.getChannelGroup().writeAndFlush(new TextWebSocketFrame(msg));
    }
}
