package org.jeecg.modules.nettyServer.service;

import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.jeecg.modules.nettyServer.domain.SocketBody;
import org.jeecg.modules.nettyServer.store.WellChannelStore;
import org.springframework.stereotype.Service;

import java.util.Enumeration;
import java.util.List;

@Service
public class PushMessageServiceImpl implements PushMessageService {
    /**
     * 推送给指定⽤户
     *
     * @param clientId 频道id
     * @param msg       消息
     */
    @Override
    public void pushMsgToOneChannel(String clientId, String msg) {
        Channel channel = WellChannelStore.getChannel(clientId);
        if(null!=channel){
            channel.writeAndFlush(new TextWebSocketFrame(msg));
        }
    }

    /**
     * 推送给指定井
     *
     * @param wellId 井号
     * @param msg      消息
     */
    @Override
    public void pushMsgToOneWell(String wellId, String msg , int type) {
        List<String> clients = WellChannelStore.getClientListByWellId(wellId);
        if(null != clients){
            clients.stream().forEach(clientId->{
                Channel channel = WellChannelStore.getChannel(clientId);


                //前端开启是否推送
                if (!this.isPullToClient(channel,type)){
                    return;
                }

                if(null != channel){
                    channel.writeAndFlush(new TextWebSocketFrame(msg));
                }
            });
        }
    }

    /**
     * 推送给所有⽤户
     *
     * @param msg 消息
     */
    @Override
    public void pushMsgToAll(String msg) {
        Enumeration<String> it = WellChannelStore.getAllClients();
        while (it.hasMoreElements()) {
            String clientId = it.nextElement();
            Channel channel = WellChannelStore.getChannel(clientId);
            if(null != channel){
                channel.writeAndFlush(new TextWebSocketFrame(msg));
            }
        }
    }

    private Boolean isPullToClient(Channel channel,int type){
        if (type == SocketBody.type_oneWellData || type == SocketBody.type_nowWellData) {
            //单井数据信息是否推送
            if (WellChannelStore.getIsPull(channel)){
                return true;
            }

        }else if (type == SocketBody.type_oneWellWarningData){
            //多井数据信息是否推送
            if (WellChannelStore.getIsWarningPull(channel)){
                return true;
            }
        }
        return false;
    }


}
