/*
 * Copyright 2011-2020 GatlingCorp (https://gatling.io)
 *
 * 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 io.gatling.http.client.body.multipart;

import io.gatling.http.client.body.RequestBody;
import io.gatling.http.client.body.RequestBodyBuilder;
import io.gatling.http.client.body.WritableContent;
import io.gatling.http.client.body.multipart.impl.MessageEndPartImpl;
import io.gatling.http.client.body.multipart.impl.MultipartChunkedInput;
import io.gatling.http.client.body.multipart.impl.PartImpl;
import io.netty.buffer.ByteBufAllocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MultipartFormDataRequestBody extends RequestBody<List<Part<?>>> {

  private static final Logger LOGGER = LoggerFactory.getLogger(MultipartFormDataRequestBody.class);

  private final byte[] boundary;

  MultipartFormDataRequestBody(List<Part<?>> content, String contentType, Charset charset, byte[] boundary) {
    super(content, contentType, charset);
    this.boundary = boundary;
  }

  @Override
  public WritableContent build(ByteBufAllocator alloc) {

    List<PartImpl> partImpls = new ArrayList<>(content.size() + 1);
    for (Part<?> part: content) {
      partImpls.add(part.toImpl(boundary));
    }
    partImpls.add(new MessageEndPartImpl(boundary));

    long contentLength = computeContentLength(partImpls);

    Object content = new MultipartChunkedInput(partImpls, contentLength);

    return new WritableContent(content, contentLength);
  }

  @Override
  public RequestBodyBuilder<List<Part<?>>> newBuilder() {
    return new MultipartFormDataRequestBodyBuilder(content);
  }

  private static long computeContentLength(List<PartImpl> partImpls) {
    try {
      long total = 0;
      for (PartImpl part : partImpls) {
        long l = part.length();
        if (l < 0) {
          return -1;
        }
        total += l;
      }
      return total;
    } catch (Exception e) {
      LOGGER.error("An exception occurred while getting the length of the parts", e);
      return 0L;
    }
  }

  @Override
  public byte[] getBytes() {
    throw new UnsupportedOperationException("MultipartFormDataRequestBody#getBytes isn't implemented yet. Contributions welcome.");
  }

  @Override
  public String toString() {
    return "MultipartFormDataRequestBody{" +
      "boundary=" + Arrays.toString(boundary) +
      ", content=" + content +
      ", contentType=" + contentType +
      ", charset=" + charset +
      '}';
  }
}

@@ -1032,37 +1032,153 @@
  io.
-netty.buffer.ByteBufAllocator
+gatling.netty.util.ByteBufUtils;%0Aimport io.netty.buffer.ByteBuf;%0Aimport io.netty.buffer.ByteBufAllocator;%0Aimport io.netty.buffer.CompositeByteBuf
 ;%0Aim
@@ -1423,16 +1423,74 @@
 ?%3E%3E%3E %7B%0A%0A
+  private static final byte%5B%5D EMPTY_BYTES = new byte%5B0%5D;%0A%0A
   privat
@@ -1809,76 +1809,57 @@
 %0A%0A  
-@Override%0A  public WritableContent build(ByteBufAllocator alloc
+private MultipartChunkedInput toChunkedInput(
 ) %7B%0A
-%0A
     
@@ -2122,29 +2122,18 @@
 s);%0A
-%0A
     
-Object content =
+return
  new
@@ -2182,16 +2182,143 @@
 ength);%0A
+  %7D%0A%0A  @Override%0A  public WritableContent build(ByteBufAllocator alloc) %7B%0A    MultipartChunkedInput content = toChunkedInput();
 %0A    ret
@@ -2349,38 +2349,41 @@
 content, content
-L
+.l
 ength
+()
 );%0A  %7D%0A%0A  @Overr
@@ -2976,135 +2976,581 @@
     
-throw new UnsupportedOperationException(%22MultipartFormDataRequestBody#getBytes isn't implemented yet. Contributions welcome.%22);
+MultipartChunkedInput content = toChunkedInput();%0A%0A    CompositeByteBuf composite = new CompositeByteBuf(ByteBufAllocator.DEFAULT, false, Integer.MAX_VALUE);%0A%0A    try %7B%0A      ByteBuf chunk;%0A      do %7B%0A        chunk = content.readChunk(ByteBufAllocator.DEFAULT);%0A        composite.addComponent(chunk);%0A      %7D while (chunk != null);%0A      return ByteBufUtils.byteBuf2Bytes(composite);%0A%0A    %7D catch (Exception e) %7B%0A      LOGGER.error(%22An exception occurred while getting the bytes of the parts%22, e);%0A      return EMPTY_BYTES;%0A%0A    %7D finally %7B%0A      composite.release();%0A    %7D
 %0A  %7D

Implement MultipartFormDataRequestBody#getBytes