package com.its.op.xnettcp.client.codec;

import com.its.utils.NettyUtils;
import com.its.utils.SysUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class NettyTcpClientDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) {

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

        int readableBytes = byteBuf.readableBytes();
        log.info("RECV_0: [{}]. ReadableBytes: {} Bytes, ReaderIndex: {}", ipAddress, readableBytes, byteBuf.readerIndex());
        if (readableBytes == 0) {
            log.error("RECV: {}. byteBuf.readableBytes() == 0.", ipAddress);
            return;
        }
//        CompositeByteBuf messageBuf = Unpooled.compositeBuffer();
//        CompositeByteBuf messageBuf = Unpooled.compositeBuffer();
//        ByteBuf headerBuf = ...;
//        ByteBuf bodyBuf = ...;
//        messageBuf.addComponents(headerBuf, bodyBuf);
//...
//        messageBuf.removeComponent(0);    // 헤더를 제거
//        for (ByteBuf buf : messageBuf) {
//            System.out.println(buf.toString());
//        }
        byteBuf.markReaderIndex();
        byte[] headBuffer = new byte[readableBytes];
        byteBuf.readBytes(headBuffer);
        log.info("RECV: [{}], {} Bytes. {}", ipAddress, headBuffer.length, SysUtils.byteArrayToHex(headBuffer));
        byteBuf.readerIndex(headBuffer.length);
        byteBuf.markReaderIndex();
        byteBuf.discardReadBytes();
        byteBuf.resetReaderIndex();

        //list.add(byteBuf);
        //ByteBuffer byteBuffer = ByteBuffer.allocate(11);
    }
}
