package com.sjkj.base_lib.net;

import android.content.res.AssetManager;
import android.util.Log;

import com.sjkj.base_lib.app.BaseApp;
import com.sjkj.base_lib.net.utils.LogInterceptor;
import com.sjkj.base_lib.net.utils.RequestInterceptor;
import com.sjkj.base_lib.utils.ToastUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Â
 * 用于获取配置好的retrofit对象
 * 参数与相应结果.
 */
public class RetrofitFactory {

    private static HashMap<String, Retrofit> retrofitHashMap = new HashMap<>();


    public static Retrofit getRetrofit(String baseUrl, boolean convert, long timeout, boolean haveToken) {
        if (baseUrl == null || baseUrl.length() <= 0)
            throw new IllegalArgumentException("Need baseUrl");

        if (!baseUrl.endsWith("/")) {
            ToastUtils.show("服务器地址须以/结尾");
            return null;
        }

        Retrofit retrofit = retrofitHashMap.get(baseUrl + String.valueOf(convert) + String.valueOf(timeout) + String.valueOf(haveToken));

        if (retrofit == null) {

            CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
            OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
                    .readTimeout(timeout, TimeUnit.SECONDS)
                    .writeTimeout(timeout, TimeUnit.SECONDS);
            // 下面两个拦截器, 用来填充和检查token
            RequestInterceptor requestInterceptor = new RequestInterceptor(BaseApp.getInstance());
            LogInterceptor logInterceptor = new LogInterceptor();
            okHttpClientBuilder.addInterceptor(requestInterceptor);
            okHttpClientBuilder.addNetworkInterceptor(logInterceptor);

            try {
                SSLContext sslContext = getSslContextForCertificateFile("supermap.cer");
                TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                trustManagerFactory.init((KeyStore) null);
                TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
                if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                    throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
                }
                X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
                okHttpClientBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);
                okHttpClientBuilder.hostnameVerifier(((hostname, session) -> true));

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                OkHttpClient client = okHttpClientBuilder.build();
                /*-------------------------------------------------------------------------------------------------------*/
                Retrofit.Builder builder = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .client(client);
                if (convert) {
                    builder.addConverterFactory(GsonConverterFactory.create()); // 与GSON的结合
                }
                retrofit = builder.build();

                retrofitHashMap.put(baseUrl, retrofit);
            }
        }
        return retrofit;
    }

    public static Retrofit getRetrofit(final String baseUrl, final boolean convert) {
        return getRetrofit(baseUrl, convert, 30L, true);
    }

    public static Retrofit getRetrofit(final String baseUrl) {
        return getRetrofit(baseUrl, true);
    }

    public static Retrofit getRetrofit(final String baseUrl, long timeout) {
        return getRetrofit(baseUrl, true, timeout, true);
    }


    /**
     * https的全局自签名证书
     */
    public static OkHttpClient.Builder setCertificates(OkHttpClient.Builder okHttpClientBuilder, InputStream... certificates) {
        SSLParams sslParams = getSslSocketFactory(null, null, certificates);
        okHttpClientBuilder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
        return okHttpClientBuilder;
    }

    //获取TrustManager
    private static X509TrustManager getTrustManager() {
        //就是把下面这个X509TrustManager更换一下
        X509TrustManager trustAllCerts = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        return trustAllCerts;
    }

    public static class SSLParams {
        public SSLSocketFactory sSLSocketFactory;
        public X509TrustManager trustManager;
    }

    public static SSLParams getSslSocketFactory(InputStream bksFile, String password, InputStream[] certificates) {
        SSLParams sslParams = new SSLParams();
        try {
            KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
            TrustManager[] trustManagers = prepareTrustManager(certificates);
            SSLContext sslContext = SSLContext.getInstance("TLS");
            X509TrustManager trustManager;
            if (trustManagers != null) {
                trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
            } else {
                trustManager = new UnSafeTrustManager();
            }
            sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
            sslParams.sSLSocketFactory = sslContext.getSocketFactory();
            sslParams.trustManager = trustManager;
            return sslParams;
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError(e);
        } catch (KeyManagementException e) {
            throw new AssertionError(e);
        } catch (KeyStoreException e) {
            throw new AssertionError(e);
        }
    }

    private static class UnSafeTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
        try {
            if (bksFile == null || password == null) return null;
            KeyStore clientKeyStore = KeyStore.getInstance("BKS");
            clientKeyStore.load(bksFile, password.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeyStore, password.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (KeyStoreException e) {
            Log.e("prepareKeyManager", e.toString());
        } catch (NoSuchAlgorithmException e) {
            Log.e("prepareKeyManager", e.toString());
        } catch (UnrecoverableKeyException e) {
            Log.e("prepareKeyManager", e.toString());
        } catch (CertificateException e) {
            Log.e("prepareKeyManager", e.toString());
        } catch (IOException e) {
            Log.e("prepareKeyManager", e.toString());
        } catch (Exception e) {
            Log.e("prepareKeyManager", e.toString());
        }
        return null;
    }

    private static TrustManager[] prepareTrustManager(InputStream... certificates) {
        if (certificates == null || certificates.length <= 0) return null;
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
                try {
                    if (certificate != null) certificate.close();
                } catch (IOException e) {
                    Log.e("prepareTrustManager", e.toString());
                }
            }
            TrustManagerFactory trustManagerFactory;
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            return trustManagerFactory.getTrustManagers();
        } catch (NoSuchAlgorithmException e) {
            Log.e("prepareTrustManager", e.toString());
        } catch (CertificateException e) {
            Log.e("prepareTrustManager", e.toString());
        } catch (KeyStoreException e) {
            Log.e("prepareTrustManager", e.toString());
        } catch (Exception e) {
            Log.e("prepareTrustManager", e.toString());
        }
        return null;
    }

    private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
        for (TrustManager trustManager : trustManagers) {
            if (trustManager instanceof X509TrustManager) {
                return (X509TrustManager) trustManager;
            }
        }
        return null;
    }

    private static class MyTrustManager implements X509TrustManager {
        private X509TrustManager defaultTrustManager;
        private X509TrustManager localTrustManager;

        public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException {
            TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            var4.init((KeyStore) null);
            defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
            this.localTrustManager = localTrustManager;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            try {
                defaultTrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException ce) {
                localTrustManager.checkServerTrusted(chain, authType);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

    private static KeyStore getKeyStore(String fileName) {
        KeyStore keyStore = null;
        try {
            AssetManager assetManager = BaseApp.getInstance().getAssets();
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = assetManager.open(fileName);
            Certificate ca;
            try {
                ca = cf.generateCertificate(caInput);
                Log.d("SslUtils", "ca=" + ((X509Certificate) ca).getSubjectDN());
            } finally {
                caInput.close();
            }
            String keyStoreType = KeyStore.getDefaultType();
            keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);
        } catch (Exception e) {
            Log.e("SslUtils", "Error during getting keystore"+ e.getMessage());
        }
        return keyStore;
    }

    public static SSLContext getSslContextForCertificateFile(String fileName) {
        try {
            KeyStore keyStore = getKeyStore(fileName);
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);
            sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
            return sslContext;
        } catch (Exception e) {
            String msg = "Error during creating SslContext for certificate from assets";
            Log.e("SslUtils", msg, e);
            throw new RuntimeException(msg);
        }
    }

}