/*
 * Copyright (c) 2012-2013 Spotify AB
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.spotify.netty.handler.codec.zmtp;


import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

/**
 * Netty encoder for ZMTP messages.
 */
class ZMTPFramingEncoder extends MessageToMessageEncoder<ZMTPMessage> {


  private final ZMTPSession session;

  public ZMTPFramingEncoder(final ZMTPSession session) {
    this.session = session;
  }

  @Override
  protected void encode(final ChannelHandlerContext ctx, final ZMTPMessage message,
                        final List<Object> out)
      throws Exception {
    // TODO (dano): integrate with write batching to avoid buffer creation and reduce garbage

    final int size = ZMTPUtils.messageSize(message, session.isEnveloped(), session.actualVersion());
    final ByteBuf buffer = Unpooled.buffer(size);

    ZMTPUtils.writeMessage(message, buffer, session.isEnveloped(), session.actualVersion());

    out.add(buffer);
  }
}

@@ -720,24 +720,79 @@
 .buffer.
-Unpooled
+ByteBufAllocator;%0Aimport io.netty.buffer.PooledByteBufAllocator
 ;%0Aimport
@@ -1042,16 +1042,60 @@
 session;
+%0A  private final ByteBufAllocator allocator;
 %0A%0A  publ
@@ -1157,26 +1157,205 @@
 this
-.session = session
+(session, PooledByteBufAllocator.DEFAULT);%0A  %7D%0A%0A  public ZMTPFramingEncoder(final ZMTPSession session, final ByteBufAllocator allocator) %7B%0A    this.session = session;%0A    this.allocator = allocator
 ;%0A  
@@ -1530,103 +1530,8 @@
 n %7B%0A
-    // TODO (dano): integrate with write batching to avoid buffer creation and reduce garbage%0A%0A
     
@@ -1658,18 +1658,25 @@
 r = 
-Unpooled.b
+allocator.directB
 uffe
@@ -1684,17 +1684,16 @@
 (size);%0A
-%0A
     ZMTP
@@ -1777,17 +1777,16 @@
 ion());%0A
-%0A
     out.

use pooled direct byte buffers