package com.ysnows.base.net;



import com.readystatesoftware.chuck.ChuckInterceptor;
import com.ysnows.base.base.BApp;

import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

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

/**
 * Created by xianguangjin on 15/12/14.
 */

public class NetEngine {

    private static OkHttpClient client = null;
    private static WeakHashMap<String, Retrofit> map = new WeakHashMap<>();


    public static Retrofit initRetrofit(String url) {
        OkHttpClient item = initClient();

        if (map.containsKey(url)) {
            return map.get(url);
        } else {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .client(item)
//                    .addConverterFactory(FastJsonConverterFactory.create())
//                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
            map.put(url, retrofit);
            return retrofit;
        }
    }

    public static OkHttpClient initClient() {
        if (client == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .readTimeout(15676, TimeUnit.MILLISECONDS)
                    .writeTimeout(156760, TimeUnit.MILLISECONDS)
                    .connectTimeout(15676, TimeUnit.MILLISECONDS)
                    .retryOnConnectionFailure(true)
//                    .addInterceptor(new ChuckerInterceptor(BApp.instance().getApplicationContext()))

                    .addInterceptor(new ChuckInterceptor( BApp.instance().getApplicationContext()))

                    // .addInterceptor(new ChuckInterceptor( BApp.instance()))
                    .cookieJar(new BCookieJar())
                    .addInterceptor(new BHeaderInterceptor());

            return client = builder.build();
        }

        return client;
    }
}
