package com.rehome.jpahefengweather.utils;


import okhttp3.*;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * Created by qhong on 2018/7/3 16:52
 **/
@Configuration
public class OkHttpConfig {
    private static OkHttpConfig okHttpConfig=null;

    public static OkHttpConfig getInstance() {
        if(okHttpConfig==null){
            okHttpConfig = new OkHttpConfig();
        }
        return okHttpConfig;
    }
    public OkHttpConfig() {}
    private OkHttpClient okHttpClient=null;
    public OkHttpClient getOkHttpClient(){
        if(okHttpClient==null){
            okHttpClient=OkHttpConfig.getInstance().okHttpClient();
        }
        return okHttpClient;
    }


    //@Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }
    //@Bean
    public SSLSocketFactory sslSocketFactory() {
        try {
            //信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * Create a new connection pool with tuning parameters appropriate for a single-user application.
     * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
     */
    //@Bean
    public ConnectionPool pool() {
        return new ConnectionPool(200, 5, TimeUnit.MINUTES);
    }
    //@Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                .addNetworkInterceptor(new TokenHeaderInterceptor())
                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
                .retryOnConnectionFailure(true)//是否开启缓存
                .connectionPool(pool())//连接池
                .connectTimeout(10L, TimeUnit.SECONDS)
                .readTimeout(30L, TimeUnit.SECONDS)
                .build();
    }
    public static class TokenHeaderInterceptor implements Interceptor {
        @NonNull
        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request originalRequest = chain.request();
            String token = JwtUtils.getJwt();
            if(token!=null){
                String credential = "Bearer " + token;
                Request updateRequest = originalRequest.newBuilder().header("Authorization", credential).build();
                return chain.proceed(updateRequest);
            }
            return chain.proceed(originalRequest);
        }
    }
}