package com.its.vds.xnettcp.center.codec;

import com.its.app.utils.NettyUtils;
import com.its.vds.xnettcp.center.handler.CenterTcpServerIdleStateHandler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;

@Slf4j
@Component
@ChannelHandler.Sharable
public class CenterTcpServerEncoder extends MessageToByteEncoder<Object> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {

        String ipAddress = NettyUtils.getRemoteIpAddress(ctx.channel());
        Channel channel = ctx.channel();

        if (!channel.isOpen() || !channel.isActive()) {
            log.error("CenterTcpServerEncoder.encode: {}, isOpen: {}, isActive: {}.", ipAddress, channel.isOpen(), channel.isActive());
            CenterTcpServerIdleStateHandler.disconnectChannel(channel);
            return;
        }

        if (!(msg instanceof ByteBuffer)) {
            log.error("CenterTcpServerEncoder.encode: {}, msg is not ByteBuffer.", ipAddress);
            CenterTcpServerIdleStateHandler.disconnectChannel(channel);
            return;
        }

        ByteBuffer buffer = (ByteBuffer)msg;
        byte[] sendBytes = buffer.array();
        out.writeBytes(sendBytes);
     }
}
