package com.gh.gamecenter.common.retrofit;

import android.content.Context;

import com.chuckerteam.chucker.api.ChuckerCollector;
import com.chuckerteam.chucker.api.ChuckerInterceptor;
import com.chuckerteam.chucker.api.RetentionManager;
import com.gh.gamecenter.Injection;

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

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by LGT on 2016/11/7.
 * Retrofit 管理工具
 */
public abstract class BaseRetrofitManager {

    public static final int NORMAL_CONN_TIME_OUT = 5;
    public static final int NORMAL_READ_TIME_OUT = 5;
    public static final int UPLOAD_CALL_TIME_OUT = 20; // 图片上传超时时间

    public static <T> T provideService(OkHttpClient client, String url, Class<T> serviceCls) {
        return new Retrofit.Builder()
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl(url).build().create(serviceCls);
    }

    public OkHttpClient getOkHttpConfig(Context context, int callTimeout, int maxRetryCount) {
        final Cache cache = new Cache(new File(OkHttpCache.getCachePath(context)), 10 * 1024 * 1024); // 10Mb

        return Injection.provideRetrofitBuilder()
                .addInterceptor(new OkHttpCacheInterceptor(context))
                .addInterceptor(new OkHttpRetryInterceptor(context, maxRetryCount))
                .addInterceptor(new ChuckerInterceptor(context, new ChuckerCollector(context, true, RetentionManager.Period.ONE_DAY)))
                .addNetworkInterceptor(new OkHttpNetworkInterceptor(context))
                .connectTimeout(NORMAL_CONN_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(NORMAL_READ_TIME_OUT, TimeUnit.SECONDS)
                .callTimeout(callTimeout, TimeUnit.SECONDS)
                .pingInterval(30, TimeUnit.SECONDS) // 加入间隔为30秒的心跳包，用于解决闲置 Http/2 连接关闭时间与服务器不一造成 Connection Timeout 的问题 (https://github.com/square/okhttp/issues/3261)
                .cache(cache)
                .build();
    }

}
