package com.njcn.gather.detection.util.socket.cilent;

import com.njcn.gather.detection.handler.SocketFreqConverterDevService;
import com.njcn.gather.detection.util.socket.FormalTestManager;
import com.njcn.gather.detection.util.socket.SocketManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 设备 Netty 客户端处理器
 */
@Slf4j
public class NettyFreqConverterDevClientHandler extends SimpleChannelInboundHandler<String> {

    private final String devChannelTag;
    private final SocketFreqConverterDevService socketFreqConverterDevService;

    public NettyFreqConverterDevClientHandler(String devChannelTag, SocketFreqConverterDevService socketFreqConverterDevService) {
        this.devChannelTag = devChannelTag;
        this.socketFreqConverterDevService = socketFreqConverterDevService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("设备连接已建立，devChannelTag={}, channelId={}", devChannelTag, ctx.channel().id());
        SocketManager.addUser(devChannelTag, ctx.channel());
        super.channelActive(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("收到设备消息，devChannelTag={}, msg={}", devChannelTag, msg);

        socketFreqConverterDevService.handleRead(devChannelTag, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.warn("设备连接已断开，devChannelTag={}", devChannelTag);
        socketFreqConverterDevService.cleanup(devChannelTag);
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("设备连接发生异常，devChannelTag={}, error={}", devChannelTag, cause.getMessage(), cause);
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                log.warn("设备连接读空闲，devChannelTag={}", devChannelTag);
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}
