package com.hymane.materialhome.api.common;

import android.util.Log;

import com.hymane.materialhome.BaseApplication;
import com.hymane.materialhome.utils.NetworkUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author   :hymanme
 * Email    :hymanme@163.com
 * Create at 2016/8/5
 * Description:
 */
public class ServiceFactory {
    private volatile static OkHttpClient okHttpClient;
    private static final int DEFAULT_CACHE_SIZE = 1024 * 1024 * 20;
    private static final int DEFAULT_MAX_AGE = 60 * 60;
    private static final int DEFAULT_MAX_STALE_ONLINE = DEFAULT_MAX_AGE * 24;
    private static final int DEFAULT_MAX_STALE_OFFLINE = DEFAULT_MAX_AGE * 24 * 7;

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (OkHttpClient.class) {
                if (okHttpClient == null) {
                    File cacheFile = new File(BaseApplication.getApplication().getCacheDir(), "responses");
                    Cache cache = new Cache(cacheFile, DEFAULT_CACHE_SIZE);
                    okHttpClient = new OkHttpClient.Builder()
                            .cache(cache)
                            .addInterceptor(REQUEST_INTERCEPTOR)
                            .addNetworkInterceptor(RESPONSE_INTERCEPTOR)
                            .addInterceptor(LoggingInterceptor)
                            .build();
                }
            }
        }
        return okHttpClient;
    }

    private static final Interceptor REQUEST_INTERCEPTOR = chain -> {
        Request request = chain.request();
        int maxStale = DEFAULT_MAX_STALE_ONLINE;
        //向服务期请求数据缓存1个小时
        CacheControl tempCacheControl = new CacheControl.Builder()
//                .onlyIfCached()
                .maxStale(5, TimeUnit.SECONDS)
                .build();
        request = request.newBuilder()
                .cacheControl(tempCacheControl)
                .build();
        return chain.proceed(request);
    };

    private static final Interceptor RESPONSE_INTERCEPTOR = chain -> {
        //针对那些服务器不支持缓存策略的情况下，使用强制修改响应头，达到缓存的效果
        Request request = chain.request();
        Response originalResponse = chain.proceed(request);
        int maxAge;
        // 缓存的数据
        if (!NetworkUtils.isConnected(BaseApplication.getApplication())) {
            maxAge = DEFAULT_MAX_STALE_OFFLINE;
        } else {
            maxAge = DEFAULT_MAX_STALE_ONLINE;
        }
        return originalResponse.newBuilder()
                .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                .removeHeader("Cache-Control")
                .header("Cache-Control", "public, max-age=" + maxAge)
                .build();
    };

    private static final Interceptor LoggingInterceptor = chain -> {
        Request request = chain.request();
        long t1 = System.nanoTime();
        Log.i("okhttp:", String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
        Response response = chain.proceed(request);
        long t2 = System.nanoTime();
        Log.i("okhttp:", String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        return response;
    };

    public static <T> T createService(String baseUrl, Class<T> serviceClazz) {
        Retrofit retrofit = new Retrofit.Builder()
                .client(getOkHttpClient())
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(serviceClazz);
    }
}
@@ -2412,16 +2412,89 @@
 %E8%BE%BE%E5%88%B0%E7%BC%93%E5%AD%98%E7%9A%84%E6%95%88%E6%9E%9C%0A
+        //%E5%93%8D%E5%BA%94%E6%8B%A6%E6%88%AA%E5%8F%AA%E4%B8%8D%E8%BF%87%E6%98%AF%E5%87%BA%E4%BA%8E%E8%A7%84%E8%8C%83%EF%BC%8C%E5%90%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%8F%91%E5%87%BA%E8%AF%B7%E6%B1%82%EF%BC%8C%E8%87%B3%E4%BA%8E%E6%9C%8D%E5%8A%A1%E5%99%A8%E6%90%AD%E4%B8%8D%E6%90%AD%E7%90%86%E6%88%91%E4%BB%AC%E6%88%91%E4%BB%AC%E4%B8%8D%E7%AE%A1%E4%BB%96%EF%BC%8C%E6%88%91%E4%BB%AC%E5%9C%A8%E5%93%8D%E5%BA%94%E9%87%8C%E9%9D%A2%E5%81%9A%E6%89%8B%E8%84%9A%EF%BC%8C%E6%9C%89%E7%BD%91%E6%B2%A1%E6%9C%89%E6%83%85%E5%86%B5%E4%B8%8B%E7%9A%84%E7%BC%93%E5%AD%98%E7%AD%96%E7%95%A5%0A
         

优化缓存策略： 若服务器不支持缓存，做到手动强制拦截缓存。 解决了豆瓣api不支持缓存的问题。 以及在无网络环境下直接使用缓存数据