package com.ifavine.pay.api;


import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.ifavine.pay.common.AppContext;
import com.ifavine.pay.common.Constants;
import com.ifavine.pay.utils.SPUtil;

import java.io.IOException;

import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

/**
 * Created by tree on 7/6/2016.
 */
public class RetrofitUtil {
    /**
     * 服务器地址
     */
    private static final String API_HOST = Constants.BASE_URL;

    private static APIService mAPIService;
    private static Retrofit mRetrofit;

    public static APIService getAPIService() {
        if (mAPIService == null) mAPIService = (APIService) getRetrofit().create(APIService.class);
        return mAPIService;
    }

    private static Retrofit getRetrofit() {
        if (mRetrofit == null) {
            ClearableCookieJar cookieJar =
                    new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(AppContext.getInstance()));
            OkHttpClient.Builder localBuilder =
                    new OkHttpClient.Builder()
                            .connectTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                            .readTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                            .writeTimeout(30 * 1000, TimeUnit.MILLISECONDS)
                            .addInterceptor(new RetryInterceptor(3))
                            .cookieJar(cookieJar)
                            // .sslSocketFactory(HttpsUtils.createSSLSocketFactory())
                            .retryOnConnectionFailure(true)
                            .addInterceptor(
                                    new Interceptor() {
                                        @Override
                                        public Response intercept(Chain chain) throws IOException {
                                            String agent = SPUtil.getInstance().readString("UserAgent");
                                            Request originRequest = chain.request();
                                            HttpUrl httpUrl = originRequest.url();
                                            String url = httpUrl.toString();
                                            Request.Builder builder = originRequest.newBuilder();
                                            builder.url(url)
                                                    .header("User-Agent", agent)
                                                    .header("Content-Type", "application/json;charset=utf-8")
                                                    .addHeader("Accept", "application/json")
                                                    .addHeader("Connection", "keep-alive");
                                            Request newRequest = builder.build();
                                            Response newResponse = chain.proceed(newRequest);
                                            return newResponse;
                                        }
                                    });


            HttpLoggingInterceptor localHttpLoggingInterceptor = new HttpLoggingInterceptor();
            localHttpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            localBuilder.addInterceptor(localHttpLoggingInterceptor).build();
            OkHttpClient client = localBuilder.build();
            mRetrofit = new Retrofit.Builder().baseUrl(API_HOST)
                    .addConverterFactory(JsonConverterFactory.create())     // 添加自定义转换器
                    .client(client).build();
            System.setProperty("java.net.preferIPv4Stack", "true");
        }

        return mRetrofit;
    }


}
