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

import org.asynchttpclient.Body;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.handler.stream.ChunkedInput;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Adapts a {@link Body} to Netty's {@link ChunkedInput}.
 */
class BodyChunkedInput
        implements ChunkedInput {

    private final Body body;

    private final int chunkSize = 1024 * 8;

    private ByteBuffer nextChunk;

    private static final ByteBuffer EOF = ByteBuffer.allocate(0);

    private boolean endOfInput = false;

    public BodyChunkedInput(Body body) {
        if (body == null) {
            throw new IllegalArgumentException("no body specified");
        }
        this.body = body;
    }

    private ByteBuffer peekNextChunk()
            throws IOException {

        if (nextChunk == null) {
            ByteBuffer buffer = ByteBuffer.allocate(chunkSize);
            long length = body.read(buffer);
            if (length < 0) {
                // Negative means this is finished
                buffer.flip();
                nextChunk = buffer;
                endOfInput = true;
            } else if (length == 0) {
                // Zero means we didn't get anything this time, but may get next time
                buffer.flip();
                nextChunk = null;
            } else {
                buffer.flip();
                nextChunk = buffer;
            }
        }
        return nextChunk;
    }

    /**
     * Having no next chunk does not necessarily means end of input, other chunks may arrive later
     */
    public boolean hasNextChunk() throws Exception {
        return peekNextChunk() != null;
    }

    public Object nextChunk() throws Exception {
        ByteBuffer buffer = peekNextChunk();
        if (buffer == null || buffer == EOF) {
            return null;
        }
        nextChunk = null;

        return ChannelBuffers.wrappedBuffer(buffer);
    }

    public boolean isEndOfInput() throws Exception {
        return endOfInput;
    }

    public void close() throws Exception {
        body.close();
    }

}

@@ -871,36 +871,8 @@
 t;%0A%0A
-import java.io.IOException;%0A
 impo
@@ -984,24 +984,16 @@
 kedInput
-%0A       
  impleme
@@ -1028,170 +1028,154 @@
 ate 
-final Body body;%0A%0A    private final int chunkSize = 1024 * 8;%0A%0A    private ByteBuffer nextChunk;%0A%0A    private static final ByteBuffer EOF = ByteBuffer.allocate(0)
+static final int DEFAULT_CHUNK_SIZE = 8 * 1024;%0A%0A    private final Body body;%0A    private final int contentLength;%0A    private final int chunkSize
 ;%0A%0A 
@@ -1207,16 +1207,8 @@
 nput
- = false
 ;%0A%0A 
@@ -1388,568 +1388,428 @@
     
-%7D%0A%0A
     
-private ByteBuffer peekNextChunk()%0A            throws IOException %7B%0A%0A        if (nextChunk == null) %7B%0A            ByteBuffer buffer = ByteBuffer.allocate(chunkSize);%0A            long length = body.read(buffer);%0A            if (length %3C 0) %7B%0A                // Negative means this is finished%0A                buffer.flip();%0A                nextChunk = buffer;%0A                endOfInput = true;%0A            %7D else if (length == 0) %7B%0A                // Zero means we didn't get anything this time, but may get next time%0A                buffer.flip();%0A    
+contentLength = (int) body.getContentLength();%0A        if (contentLength %3C= 0)%0A            chunkSize = DEFAULT_CHUNK_SIZE;%0A        else%0A            chunkSize = Math.min(contentLength, DEFAULT_CHUNK_SIZE);%0A    %7D%0A%0A    public boolean hasNextChunk() throws Exception %7B%0A        // unused%0A        throw new UnsupportedOperationException();%0A    %7D%0A%0A    public Object nextChunk() throws Exception %7B%0A        if (endOfInput) %7B%0A
     
@@ -1820,30 +1820,21 @@
     
-nextChunk =
+return
  null;%0A
-    
     
@@ -1862,61 +1862,98 @@
     
-    buffer.flip();%0A                nextChunk = 
+ByteBuffer buffer = ByteBuffer.allocate(chunkSize);%0A            long r = body.read(
 buffer
+)
 ;%0A  
@@ -1966,254 +1966,79 @@
     
-%7D%0A        %7D%0A        return nextChunk;%0A    %7D%0A
+if (r %3C 0L) %7B
 %0A    
-/**%0A
      
-* Having no next chunk does not necessarily means end of input, other chunks may arrive later
+       endOfInput = true;
 %0A     
-*/%0A
     
-public boolean hasNextChunk() throws Exception %7B%0A        return peekNextChunk() !=
+       return
  nul
@@ -2048,214 +2048,151 @@
     
-%7D%0A%0A
     
-public Object nextChunk() throws Exception %7B%0A        ByteBuffer buffer = peekNextChunk();%0A        if (buffer == null %7C%7C buffer == EOF) %7B%0A            return null;%0A        %7D%0A        nextChunk = null;%0A%0A
+    %7D else %7B%0A                endOfInput = r == contentLength %7C%7C r %3C chunkSize && contentLength %3E 0;%0A                buffer.flip();%0A        
     
@@ -2236,24 +2236,48 @@
 er(buffer);%0A
+            %7D%0A        %7D%0A
     %7D%0A%0A    p
@@ -2316,32 +2316,89 @@
 ows Exception %7B%0A
+        // called by ChunkedWriteHandler AFTER nextChunk%0A
         return e
@@ -2486,11 +2486,10 @@
 ;%0A    %7D%0A
-%0A
 %7D%0A

Refactor BodyChunkedInput