package com.sibilantsolutions.grison.net.netty.codec;

import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;

import com.sibilantsolutions.grison.driver.foscam.dto.CommandDto;
import com.sibilantsolutions.grison.net.netty.codec.dto.FoscamTextByteBufDTO;
import com.sibilantsolutions.grison.net.netty.codec.parse.NettyFosTypeWriter;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

@ChannelHandler.Sharable
public class FoscamTextByteBufDTOEncoder extends MessageToByteEncoder<FoscamTextByteBufDTO> {

    @Override
    public void encode(ChannelHandlerContext ctx, FoscamTextByteBufDTO msg, ByteBuf out) {
        out.writeBytes(msg.opCode().protocol.getValue());   //4
        NettyFosTypeWriter.write(msg.opCode().value, out);  //2
        NettyFosTypeWriter.write(CommandDto.RESERVE1, out); //1
        out.writeBytes(CommandDto.RESERVE2);                //8
        NettyFosTypeWriter.write(msg.encodedLength(), out); //4
        NettyFosTypeWriter.write(msg.encodedLength(), out); //4
        out.writeBytes(msg.textBuf());                      //N

        // Each FoscamTextByteBufDTO has a ByteBuf that was allocated to hold the text; it is our job to release it.
        msg.textBuf().release();
    }

    @Override
    protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, FoscamTextByteBufDTO msg, boolean preferDirect) {
        return allocateBuf(ctx, msg);
    }

    public static ByteBuf allocateBuf(ChannelHandlerContext ctx, FoscamTextByteBufDTO msg) {
        return ctx.alloc().buffer(CommandDto.COMMAND_PREFIX_LENGTH + checkPositiveOrZero(msg.encodedLength().value().intValue(), "encodedLength"));
    }
}

@@ -733,24 +733,42 @@
 eBuf out) %7B%0A
+        try %7B%0A    
         out.
@@ -819,32 +819,36 @@
 ;   //4%0A        
+  
+  
 NettyFosTypeWrit
@@ -887,32 +887,36 @@
 );  //2%0A        
+   
+ 
 NettyFosTypeWrit
@@ -955,16 +955,20 @@
 t); //1%0A
+    
         
@@ -1023,32 +1023,36 @@
     //8%0A        
+    
 NettyFosTypeWrit
@@ -1091,32 +1091,36 @@
 t); //4%0A        
+ 
+   
 NettyFosTypeWrit
@@ -1159,32 +1159,36 @@
 t); //4%0A        
+  
+  
 out.writeBytes(m
@@ -1227,17 +1227,40 @@
     //N%0A
-%0A
+        %7D finally %7B%0A    
         
@@ -1376,16 +1376,20 @@
         
+    
 msg.text
@@ -1405,16 +1405,26 @@
 ease();%0A
+        %7D%0A
     %7D%0A%0A 

Use finally block to make sure we release given msg's buffer -- assuming we make it this far.