package com.zksy.environmentHJ212.config;

import com.zksy.environmentHJ212.utils.MonitorDatasynch;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;

@Slf4j
@Component
public class ServerHandler extends ChannelInboundHandlerAdapter {
    private static ServerHandler serverHandler;

    @Autowired
    private MonitorDatasynch monitorDatasynch;

    @PostConstruct
    public void init() {
        log.info("init()方法");
        serverHandler = this;
        serverHandler.monitorDatasynch = this.monitorDatasynch;
    }

    /**
     * 客户端与服务端创建连接的时候调用
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端与服务端连接开始...");
        NettyConfig.group.add(ctx.channel());
        // 往客户端发送消息的代码（注释部分）若启用，也需注意ByteBuf释放
    }

    /**
     * 客户端与服务端断开连接时调用
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端与服务端连接关闭...");
        NettyConfig.group.remove(ctx.channel());
    }

    /**
     * 服务端接收客户端发送过来的数据结束之后调用
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
        log.info("信息接收完毕...");
    }

    /**
     * 工程出现异常的时候调用
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生异常", cause);
        ctx.close();
    }

    /**
     * 服务端处理客户端请求的核心方法
     */
    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object info) throws Exception {
        try {
            ByteBuf buf = (ByteBuf) info;
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String msg = new String(req);
            log.info("接收数据: {}, 时间: {}", msg, LocalDateTime.now());

            // 调用业务方法处理数据
            String pushMonitorDataStr = serverHandler.monitorDatasynch.pushMonitorData(channelHandlerContext, msg);
        } catch (Exception e) {
            log.error("数据处理错误", e);
        } finally {
            ReferenceCountUtil.release(info);
            channelHandlerContext.flush();
        }
    }
}
