package com.sxyz.rfid.retrofit.http;

import android.text.TextUtils;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.sxyz.rfid.App;
import com.sxyz.rfid.AppConfig;
import com.sxyz.rfid.presenter.service.ApiService;
import com.sxyz.rfid.utils.LocalUtils;

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

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * @Description: Incremental change is better than ambitious failure.
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */

public class RetrofitUtils {

    public static final String TAG = "xxx";
    private static final long DEFAULT_TIMEOUT = 100000L;
    private volatile static RetrofitUtils apiEngine;
    private Retrofit retrofit;
    private HashMap<Object, Call> callMap = new HashMap<>();

    private RetrofitUtils() {

        OkHttpClient client;
        if (AppConfig.DEBUG) {
            client = getHttpsClient();
        } else {
            client = new OkHttpClient.Builder()
                    .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
//                    .addNetworkInterceptor(new NetCacheInterceptor())
//                    .addNetworkInterceptor(new NoNetCacheInterceptor())
//                    .addInterceptor(new InterceptorUtil())
                    .addInterceptor(new OkLogInterceptor())
                    .cache(new Cache(new File(App.getContext().getCacheDir(), "OkHttpCache"), 1024 * 1024 * 100))
                    .build();
        }

        retrofit = new Retrofit.Builder()
//                .baseUrl(AppConfig.BASE_URL)
                .baseUrl(TextUtils.isEmpty(App.ip) ? AppConfig.BASE_URL : LocalUtils.getIpPort())
                .client(client)
                //然后将下面的GsonConverterFactory.create()替换成我们自定义的ResponseConverterFactory.create()
//                .addConverterFactory(ResponseConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

    }

    public ApiService getApiService() {
        return retrofit.create(ApiService.class);
    }

    private OkHttpClient getHttpsClient() {
        OkHttpClient.Builder okhttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
//                .addNetworkInterceptor(new NetCacheInterceptor())
//                .addNetworkInterceptor(new NoNetCacheInterceptor())
//                .addInterceptor(new InterceptorUtil())
                .addInterceptor(new OkLogInterceptor())
                .cache(new Cache(new File(App.getContext().getCacheDir(), "OkHttpCache"), 1024 * 1024 * 100));
        //信任所有服务器地址
        okhttpClient.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                //设置为true
                return true;
            }
        });
        //创建管理器
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] x509Certificates,
                    String s) throws java.security.cert.CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
        }};
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            //为OkHttpClient设置sslSocketFactory
            okhttpClient.sslSocketFactory(sslContext.getSocketFactory());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return okhttpClient.build();
    }

    public static RetrofitUtils getInstance() {
        if (apiEngine == null) {
            synchronized (RetrofitUtils.class) {
                if (apiEngine == null) {
                    apiEngine = new RetrofitUtils();
                }
            }
        }
        return apiEngine;
    }

    public HashMap<Object, Call> getCallMap() {
        return callMap;
    }

}
