/*
 * Copyright 2017 JessYan
 *
 * 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 com.jess.arms.http;

import android.os.Build;
import android.support.annotation.NonNull;
import android.util.Log;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.HttpException;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.util.ContentLengthInputStream;
import com.bumptech.glide.util.Synthetic;

import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Fetches an {@link InputStream} using the okhttp library.
 */
public class OkHttpStreamFetcher implements DataFetcher<InputStream>,
        okhttp3.Callback {
    private static final String TAG = "OkHttpFetcher";
    private final Call.Factory client;
    private final GlideUrl url;
    @Synthetic InputStream stream;
    @Synthetic ResponseBody responseBody;
    private volatile Call call;
    private DataCallback<? super InputStream> callback;

    public OkHttpStreamFetcher(Call.Factory client, GlideUrl url) {
        this.client = client;
        this.url = url;
    }

    @Override
    public void loadData(Priority priority, final DataCallback<? super InputStream> callback) {
        Request.Builder requestBuilder = new Request.Builder().url(url.toStringUrl());
        for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
            String key = headerEntry.getKey();
            requestBuilder.addHeader(key, headerEntry.getValue());
        }
        Request request = requestBuilder.build();
        this.callback = callback;

        call = client.newCall(request);
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            call.enqueue(this);
        } else {
            try {
                // Calling execute instead of enqueue is a workaround for #2355, where okhttp throws a
                // ClassCastException on O.
                onResponse(call, call.execute());
            } catch (IOException e) {
                onFailure(call, e);
            } catch (ClassCastException e) {
                // It's not clear that this catch is necessary, the error may only occur even on O if
                // enqueue is used.
                onFailure(call, new IOException("Workaround for framework bug on O", e));
            }
        }
    }

    @Override
    public void onFailure(Call call, IOException e) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "OkHttp failed to obtain result", e);
        }

        callback.onLoadFailed(e);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        responseBody = response.body();
        if (response.isSuccessful()) {
            long contentLength = responseBody.contentLength();
            stream = ContentLengthInputStream.obtain(responseBody.byteStream(), contentLength);
            callback.onDataReady(stream);
        } else {
            callback.onLoadFailed(new HttpException(response.message(), response.code()));
        }
    }

    @Override
    public void cleanup() {
        try {
            if (stream != null) {
                stream.close();
            }
        } catch (IOException e) {
            // Ignored
        }
        if (responseBody != null) {
            responseBody.close();
        }
        callback = null;
    }

    @Override
    public void cancel() {
        Call local = call;
        if (local != null) {
            local.cancel();
        }
    }

    @NonNull
    @Override
    public Class<InputStream> getDataClass() {
        return InputStream.class;
    }

    @NonNull
    @Override
    public DataSource getDataSource() {
        return DataSource.REMOTE;
    }
}


@@ -618,33 +618,8 @@
 p;%0A%0A
-import android.os.Build;%0A
 impo
@@ -992,25 +992,29 @@
 de.util.
-Synthetic
+Preconditions
 ;%0A%0Aimpor
@@ -1324,24 +1324,16 @@
 Stream%3E,
-%0A       
  okhttp3
@@ -1474,26 +1474,23 @@
 rl;%0A    
-@Synthetic
+private
  InputSt
@@ -1510,18 +1510,15 @@
     
-@Synthetic
+private
  Res
@@ -1557,84 +1557,328 @@
 ate 
-volatile Call
+DataCallback%3C? super InputStream%3E
  call
+back
 ;%0A    
-private DataCallback%3C? super InputStream%3E callback;%0A
+// call may be accessed on the main thread while the object is in use on other threads. All other%0A    // accesses to variables may occur on different threads, but only one at a time.%0A    private volatile Call call;%0A%0A    // Public API.%0A    @SuppressWarnings(%22WeakerAccess%22)
 %0A   
@@ -2042,16 +2042,25 @@
 oadData(
+@NonNull 
 Priority
@@ -2069,16 +2069,50 @@
 riority,
+%0A                         @NonNull
  final D
@@ -2588,754 +2588,103 @@
     
-if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) %7B%0A            call.enqueue(this);%0A        %7D else %7B%0A            try %7B%0A                // Calling execute instead of enqueue is a workaround for #2355, where okhttp throws a%0A                // ClassCastException on O.%0A                onResponse(call, call.execute());%0A            %7D catch (IOException e) %7B%0A                onFailure(call, e);%0A            %7D catch (ClassCastException e) %7B%0A                // It's not clear that this catch is necessary, the error may only occur even on O if%0A                // enqueue is used.%0A                onFailure(call, new IOException(%22Workaround for framework bug on O%22, e));%0A            %7D%0A        %7D%0A    %7D%0A%0A    @Override%0A    public void onFailure(Call call,
+call.enqueue(this);%0A    %7D%0A%0A    @Override%0A    public void onFailure(@NonNull Call call, @NonNull
  IOE
@@ -2897,16 +2897,25 @@
 esponse(
+@NonNull 
 Call cal
@@ -2916,16 +2916,25 @@
 ll call,
+ @NonNull
  Respons
@@ -2948,27 +2948,8 @@
 nse)
- throws IOException
  %7B%0A 
@@ -3059,16 +3059,43 @@
 ength = 
+Preconditions.checkNotNull(
 response
@@ -3098,16 +3098,17 @@
 onseBody
+)
 .content
@@ -4060,10 +4060,8 @@
 %0A    %7D%0A%7D
-%0A%0A

Improve OkHttpStreamFetcher