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


import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ReplayingDecoder;

/**
 * An abstract base class for common functionality to the ZMTP codecs.
 */
abstract class CodecBase extends ReplayingDecoder<Void> {

  protected final ZMTPSession session;
  protected HandshakeListener listener;

  CodecBase(ZMTPSession session) {
    this.session = session;
  }

  @Override
  public void channelActive(final ChannelHandlerContext ctx) throws Exception {

    setListener(new HandshakeListener() {
      @Override
      public void handshakeDone(int protocolVersion, byte[] remoteIdentity) {
        session.remoteIdentity(remoteIdentity);
        session.actualVersion(protocolVersion);
        updatePipeline(ctx.pipeline(), session);
        ctx.fireChannelActive();
      }
    });

    ctx.writeAndFlush(onConnect());
    this.session.channel(ctx.channel());
  }

  abstract ByteBuf onConnect();

  abstract boolean inputOutput(final ByteBuf buffer, final ChannelHandlerContext ctx)
      throws ZMTPException;

  @Override
  protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
      throws Exception {

    in.markReaderIndex();
    boolean done = inputOutput(in, ctx);
    if (!done) {
      return;
    }

    // This follows the pattern for dynamic pipelines documented in
    // http://netty.io/4.0/api/io/netty/handler/codec/ReplayingDecoder.html
    if (actualReadableBytes() > 0) {
      out.add(in.readBytes(actualReadableBytes()));
    }
  }

  void setListener(HandshakeListener listener) {
    this.listener = listener;
  }


  private void updatePipeline(ChannelPipeline pipeline,
                              ZMTPSession session) {
    final ChannelHandlerContext ctx = pipeline.context(this);
    pipeline.addAfter(ctx.executor(), ctx.name(), "zmtpEncoder",
                      new ZMTPFramingEncoder(session));
    pipeline.addAfter(ctx.executor(), "zmtpEncoder", "zmtpDecoder",
                      new ZMTPFramingDecoder(session));
    pipeline.remove(this);
  }

  /**
   * Parse and return the remote identity octets from a ZMTP/1.0 greeting.
   */
  static byte[] readZMTP1RemoteIdentity(final ByteBuf buffer) throws ZMTPException {
    buffer.markReaderIndex();

    final long len = ZMTPUtils.decodeLength(buffer);
    if (len > 256) {
      // spec says the ident string can be up to 255 chars
      throw new ZMTPException("Remote identity longer than the allowed 255 octets");
    }

    // Bail out if there's not enough data
    if (len == -1 || buffer.readableBytes() < len) {
      buffer.resetReaderIndex();
      throw new IndexOutOfBoundsException("not enough data");
    }
    // skip the flags byte
    buffer.skipBytes(1);

    if (len == 1) {
      return null;
    }
    final byte[] identity = new byte[(int) len - 1];
    buffer.readBytes(identity);
    return identity;
  }
}

@@ -186,16 +186,70 @@
 peline;%0A
+import io.netty.channel.CombinedChannelDuplexHandler;%0A
 import i
@@ -1917,128 +1917,51 @@
     
-final ChannelHandlerContext ctx = pipeline.context(this);%0A    pipeline.addAfter(ctx.executor(), ctx.name()
+pipeline.replace(%0A        this
 , %22zmtp
-En
+-
 code
-r
+c
 %22,%0A 
@@ -1971,134 +1971,82 @@
     
-              new ZMTPFramingEncoder(session));%0A    pipeline.addAfter(ctx.executor(), %22zmtpEn
+new CombinedChannelDuplexHandler%3CZMTPFramingDe
 coder
-%22
 , 
-%22zmtpDecoder%22,%0A          
+ZMTPFramingEncoder%3E(%0A
     
@@ -2088,35 +2088,54 @@
 ion)
-);
+,
 %0A    
-pipeline.remove(this
+        new ZMTPFramingEncoder(session))
 );%0A 

combine encoder and decoder in a duplex handler