package com.njcn.gather.detection.util.business;

import com.njcn.gather.detection.pojo.constant.DetectionCommunicateConstant;
import com.njcn.gather.detection.pojo.param.PreDetectionParam;
import com.njcn.gather.detection.util.socket.CnSocketUtil;
import com.njcn.gather.detection.util.socket.SocketManager;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 检测通讯工具类
 *
 * @author hongawen
 * @version 1.0
 * @data 2025/4/15 15:24
 */
@Slf4j
public class DetectionCommunicateUtil {


    /**
     * 检测是否存在连接的源、设备通讯的模块通道
     * 有则强行关闭
     */
    public static void checkCommunicateChannel(PreDetectionParam param) {
        Channel channelSource = SocketManager.getChannelByUserId(param.getUserPageId() + DetectionCommunicateConstant.SOURCE);
        Channel channelDev = SocketManager.getChannelByUserId(param.getUserPageId() + DetectionCommunicateConstant.DEV);

        boolean channelSourceActive = channelSource != null && channelSource.isActive();
        boolean channelDevActive = channelDev != null && channelDev.isActive();
        if(channelSourceActive || channelDevActive){
            if(channelSourceActive){
                System.out.println("发送关闭源指令。。。。。。。。");
                CnSocketUtil.quitSendSource(param);
            }

            if(channelDevActive){
                System.out.println("发送关闭设备通讯指令。。。。。。。。");
                CnSocketUtil.quitSend(param);
            }
            // 休眠4秒
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                log.error(e.getMessage());
            }
        }



//        SocketManager.removeUser(param.getUserPageId() + DetectionCommunicateConstant.SOURCE);
//        SocketManager.removeUser(param.getUserPageId() + DetectionCommunicateConstant.DEV);


    }


    /**
     * 比对式-检测是否存在已有的Socket通道，有则强行关闭
     *
     * @param loginName
     */
//    public static void checkContrastCommunicateChannel(String loginName) {
//        Channel channel = SocketManager.getChannelByUserId(loginName + CnSocketUtil.CONTRAST_DEV_TAG);
//
//        if (Objects.nonNull(channel) && channel.isActive()) {
//            System.out.println("存在已有的Socket通道，强行关闭。。。。。。。。");
//            CnSocketUtil.contrastSendquit(loginName);
//            SocketManager.removeUser(loginName + CnSocketUtil.CONTRAST_DEV_TAG);
//            try {
//                Thread.sleep(4000);
//            } catch (InterruptedException e) {
//                log.error(e.getMessage());
//            }
//        }
//    }
}
