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

import com.docus.server.common.netty.Payload;
import com.docus.server.common.netty.server.ChannelRepository;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * 业务消息处理
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class NettyBusinessHandler extends SimpleChannelInboundHandler<Payload.Message> {

    @Resource
    private ChannelRepository repository;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Payload.Message message) {
        if (message.getCmd() == Payload.Message.type.AUTH) {
            log.info("接受到工控机<{}>的认证消息：{}", message.getClient(), message.getContent());
            InetSocketAddress ipSocket = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
            String clientIp = ipSocket.getAddress().getHostAddress();
            log.info("工控机:{}，连接上线,IP地址信息:{}", message.getClient(), clientIp);
            Channel channel = repository.get(message.getClient());
            if (channel != null && channel.isOpen()) {
                channel.close();
            }
            repository.put(message.getClient(), channelHandlerContext.channel());
        }
        if (message.getCmd() == Payload.Message.type.PRINT_DONE) {
            log.info("接受到打印回馈指令，内容{}", message.getContent());
        }
        if (message.getCmd() == Payload.Message.type.WHATEVER) {
            log.info("收到测试消息：{}", message.getContent());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        if (channel.isActive()) {
            ctx.close();
        }
        super.exceptionCaught(ctx, cause);
    }
}
