package io.shardingjdbc.server.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.shardingjdbc.server.packet.AbstractMySQLPacket;
import io.shardingjdbc.server.packet.MySQLPacketPayload;
import io.shardingjdbc.server.packet.AbstractMySQLSentPacket;

import java.util.List;

/**
 * MySQL packet codec.
 * 
 * @author zhangliang 
 */
public final class MySQLPacketCodec extends ByteToMessageCodec<AbstractMySQLSentPacket> {
    
    @Override
    protected void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) throws Exception {
        int readableBytes = in.readableBytes();
        if (readableBytes < AbstractMySQLPacket.PAYLOAD_LENGTH) {
            return;
        }
        int payloadLength = in.markReaderIndex().readMediumLE();
        if (readableBytes < payloadLength) {
            in.resetReaderIndex();
            return;
        }
        out.add(in);
    }
    
    @Override
    protected void encode(final ChannelHandlerContext context, final AbstractMySQLSentPacket message, final ByteBuf out) throws Exception {
        MySQLPacketPayload mysqlPacketPayload = new MySQLPacketPayload(context.alloc().buffer());
        message.write(mysqlPacketPayload);
        out.writeMediumLE(mysqlPacketPayload.getByteBuf().readableBytes());
        out.writeByte(message.getSequenceId());
        out.writeBytes(mysqlPacketPayload.getByteBuf());
    }
}

@@ -64,16 +64,52 @@
 yteBuf;%0A
+import io.netty.buffer.ByteBufUtil;%0A
 import i
@@ -147,16 +147,16 @@
 ontext;%0A
-
 import i
@@ -373,16 +373,50 @@
 tPacket;
+%0Aimport lombok.extern.slf4j.Slf4j;
 %0A%0Aimport
@@ -491,16 +491,23 @@
 ng %0A */%0A
+@Slf4j%0A
 public f
@@ -867,32 +867,107 @@
 turn;%0A        %7D%0A
+        log.error(%22Read from client: %5Cn%22 + ByteBufUtil.prettyHexDump(in));%0A
         int payl
@@ -1572,24 +1572,24 @@
 uenceId());%0A
-
         out.
@@ -1629,20 +1629,95 @@
 ByteBuf());%0A
+        log.error(%22Write to client: %5Cn%22 + ByteBufUtil.prettyHexDump(out));%0A
     %7D%0A%7D%0A

add log for read/write