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

import com.njzscloud.common.localizer.DeviceStore;
import com.njzscloud.common.localizer.Localizer;
import com.njzscloud.common.localizer.jt808.JT808;
import com.njzscloud.common.localizer.jt808.message.JT808Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
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;
            String terminalPhone = message.getTerminalPhone();
            Localizer localizer = DeviceStore.determineLocalizer(terminalPhone);
            if (localizer == null) {
                log.warn("设备不存在：{}", terminalPhone);
                ctx.channel().close();
                return;
            }
            int messageId = message.getMessageId();
            if (messageId == 0x0100) {
                log.info("客户端连接: {}   {}", terminalPhone, ctx.channel().remoteAddress());
                JT808.register(terminalPhone, ctx.channel());
            }
            JT808MessageCenter.dispatch(message);
        } else {
            super.channelRead(ctx, msg);
        }
    }

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

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel = ctx.channel();
        log.error("发生异常: {}，{}", channel == null ? "无IP" : channel.remoteAddress(), cause.getMessage(), cause);
        ctx.close();
    }
}
