package com.nytimes.android.external.store3.middleware.moshi;

import com.nytimes.android.external.fs3.BufferedSourceAdapter;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import java.io.ByteArrayInputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import javax.annotation.Nonnull;
import javax.inject.Inject;

import okio.BufferedSource;
import okio.Okio;

/**
 * An implementation of {@link BufferedSourceAdapter BufferedSourceAdapter} that uses
 * {@link Moshi} to convert Java values to JSON.
 */
public class MoshiBufferedSourceAdapter<Parsed> implements BufferedSourceAdapter<Parsed> {

    private final JsonAdapter<Parsed> jsonAdapter;

    @Inject
    public MoshiBufferedSourceAdapter(@Nonnull Moshi moshi, @Nonnull Type type) {
        this.jsonAdapter = moshi.adapter(type);
    }

    @Nonnull
    @Override
    public BufferedSource toJson(@Nonnull Parsed value) {
        return Okio.buffer(Okio.source(new ByteArrayInputStream(jsonAdapter.toJson(value).getBytes(
                Charset.forName("UTF-8")))));
    }
}

@@ -187,25 +187,24 @@
 oshi.Moshi;%0A
-%0A
 import java.
@@ -206,36 +206,27 @@
 java.io.
-ByteArrayInputStream
+IOException
 ;%0Aimport
@@ -254,42 +254,8 @@
 pe;%0A
-import java.nio.charset.Charset;%0A%0A
 impo
@@ -311,16 +311,35 @@
 Inject;%0A
+import okio.Buffer;
 %0Aimport 
@@ -362,26 +362,8 @@
 rce;
-%0Aimport okio.Okio;
 %0A%0A/*
@@ -893,99 +893,204 @@
     
-return Okio.buffer(Okio.source(new ByteArrayInputStream(jsonAdapter.toJson(value).getBytes(
+Buffer buffer = new Buffer();%0A        try %7B%0A            jsonAdapter.toJson(buffer, value);%0A        %7D catch (IOException e) %7B%0A            throw new AssertionError(e); // No I/O writing to a Buffer.
 %0A   
@@ -1094,24 +1094,26 @@
         
+%7D%0A
         
 Charset.
@@ -1108,36 +1108,21 @@
     
-Charset.forName(%22UTF-8%22)))))
+return buffer
 ;%0A  

Remove intermediate streams. (#247)