package com.docus.server.common.netty.server.handler;

import com.docus.server.common.CommMsg;
import com.docus.server.common.MsgConstants;
import com.docus.server.common.netty.server.TerminalToChannelCacheMap;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.net.InetSocketAddress;

/**
 * 客户端和服务端心跳
 */
@Slf4j
@ChannelHandler.Sharable
public class NettyHeartbeatHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        CommMsg commMsg = (CommMsg) msg;
        String messageType = commMsg.getMessageType();
        String messageTime = commMsg.getMessageTime();
        Serializable messageContent = commMsg.getContent();

        if (messageType.equals(MsgConstants.HEARTBEAT_REQUEST)) {

            log.info("======== 【调度器服务端-收到终端消息】, 消息时间={}, 消息类型={}, 消息内容={}", messageTime, messageType, messageContent + " ======== ");

            InetSocketAddress ipSocket = (InetSocketAddress) ctx.channel().remoteAddress();
            String clientIp = ipSocket.getAddress().getHostAddress();
            log.info("接收到客户端的心跳，【调度器-终端IP】:{}，连接上线,IP地址信息:{}", clientIp, clientIp);

        } else {

            if (ctx.channel().isOpen()) {
                //触发下一个handler
                ctx.fireChannelRead(msg);
            }
        }
    }

    private TerminalToChannelCacheMap repository;

    public NettyHeartbeatHandler(TerminalToChannelCacheMap repository) {
        this.repository = repository;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        String clientId = repository.getClientKey(ctx.channel());
        log.error("通道发生异常，终端连接：{}", clientId);
        //移除终端，终端离线
        if (clientId != null) {
            repository.remove(clientId);
        }
        if (ctx.channel().isActive()) {
            ctx.close();
        }
        super.exceptionCaught(ctx, cause);
    }
}
