/**
 * Copyright (c) 2015-2016 Silk Labs, Inc.
 * All Rights Reserved.
 */

package com.silklabs.react.blobs;

import android.content.ContentProviderClient;
import android.content.ContentResolver;

import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;

import java.nio.ByteBuffer;

public class BlobModule extends ReactContextBaseJavaModule {

  private ReactContext mReactContext;
  private BlobProvider mBlobProvider;

  public BlobModule(ReactApplicationContext reactContext) {
    super(reactContext);
    mReactContext = reactContext;
    initializeBlobProvider();
  }

  private void initializeBlobProvider() {
    ContentResolver resolver = mReactContext.getContentResolver();
    ContentProviderClient client = resolver.acquireContentProviderClient(BlobProvider.AUTHORITY);
    if (client == null) {
      return;
    }
    mBlobProvider = (BlobProvider)client.getLocalContentProvider();
    client.release();
  }

  @Override
  public String getName() {
    return "SLKBlobManager";
  }

  @ReactMethod
  public void createFromParts(ReadableArray parts, String blobId) {
    int totalSize = 0;
    for (int i = 0; i < parts.size(); i++) {
      ReadableMap part = parts.getMap(i);
      totalSize += part.getInt("size");
    }
    ByteBuffer buffer = ByteBuffer.allocate(totalSize);
    for (int i = 0; i < parts.size(); i++) {
      buffer.put(mBlobProvider.resolve(parts.getMap(i)));
    }
    mBlobProvider.store(buffer.array(), blobId);
  }

  @ReactMethod
  public void release(String blobId) {
    mBlobProvider.release(blobId);
  }

}

@@ -525,16 +525,44 @@
 eBuffer;
+%0Aimport java.util.ArrayList;
 %0A%0Apublic
@@ -1362,24 +1362,28 @@
    int total
+Blob
 Size = 0;%0A  
@@ -1380,16 +1380,85 @@
 ze = 0;%0A
+    ArrayList%3CReadableMap%3E partList = new ArrayList%3C%3E(parts.size());%0A
     for 
@@ -1543,24 +1543,28 @@
 %0A      total
+Blob
 Size += part
@@ -1580,16 +1580,45 @@
 size%22);%0A
+      partList.add(i, part);%0A
     %7D%0A  
@@ -1664,16 +1664,20 @@
 te(total
+Blob
 Size);%0A 
@@ -1688,40 +1688,35 @@
 or (
-int i = 0; i %3C parts.size(); i++
+ReadableMap part : partList
 ) %7B%0A
@@ -1758,27 +1758,16 @@
 lve(part
-s.getMap(i)
 ));%0A    

Fix new Blob([...]) on Android