package com.njzscloud.common.localizer.jt808.support;

import com.njzscloud.common.localizer.jt808.JT808;
import com.njzscloud.common.localizer.jt808.message.JT808Message;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

/**
 * JT808消息处理器，处理解码后的消息并发送响应
 */
@Slf4j
public class JT808MessageHandler extends ChannelInboundHandlerAdapter {
    // 管理所有连接的客户端
    private static final ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端连接: {}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof JT808Message) {
            JT808Message message = (JT808Message) msg;
            int messageId = message.getMessageId();
            // log.info("收到消息, 设备号： {}，消息ID: 0x{}, 流水号: {}", message.getTerminalPhone(), Integer.toHexString(messageId), message.getFlowId());
            if (messageId == 0x0100) {
                JT808.register(message.getTerminalPhone(), ctx.channel());
            }
            JT808MessageResolver.dispatchMsg(messageId, message);
        } else {
            super.channelRead(ctx, msg);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端断开连接: {}", ctx.channel().remoteAddress());
        clients.remove(ctx.channel());
        JT808.unregister(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生异常: {}", cause.getMessage(), cause);
        ctx.close();
    }
}
