package com.ygtx.emcs.util;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;

import com.ygtx.emcs.activity.model.EventMessage;

import org.apache.log4j.Logger;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
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 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;

public class HttpsUtil {

    public static Logger mylog =Logger.getLogger(HttpsUtil.class);

    /**
     * 获取双向认证的SSLSocketFactory
     *
     * @param needTrustServerCers 需要信任的所有服务器端公钥cer文件
     * @param clientBks           客户端bks密钥库
     * @param clientBksPassword   客户端bks密钥库的密码
     * @return 双向认证的SSLSocketFactory
     */
    public static SSLSocketFactory getSslSocketFactory(InputStream[] needTrustServerCers, InputStream clientBks,
                                                       String clientBksPassword) {
        try {
            // 信任服务器端公钥管理器列表
            TrustManager[] trustManagers = prepareTrustManager(needTrustServerCers);
            Log.i("aa","trustManagers:"+trustManagers.length);
            // 当前客户端bks密钥库的所有证书管理器
            KeyManager[] keyManagers = prepareKeyManager(clientBks, clientBksPassword);
            // SSLContext
            SSLContext sslContext = SSLContext.getInstance("TLS");
            // 初始化
            sslContext.init(keyManagers, new TrustManager[]{new DefaultTrustManager(chooseX509TrustManager
                    (trustManagers))}, new SecureRandom());
            // 得到SSLSocketFactory
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            return sslSocketFactory;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取单向认证的SSLSocketFactory
     *
     * @param needTrustServerCers 需要信任的所有服务器端公钥cer文件
     * @return 单向认证的SSLSocketFactory
     */
    public static SSLSocketFactory getSslSocketFactory(InputStream[] needTrustServerCers) {
        return getSslSocketFactory(needTrustServerCers, null, null);
    }

    private static TrustManager[] prepareTrustManager(InputStream[] needTrustServerCers) {

        if (needTrustServerCers == null || needTrustServerCers.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 : needTrustServerCers) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
                try {
                    if (certificate != null) {
                        certificate.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            TrustManagerFactory trustManagerFactory = null;
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keyStore);

            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            return trustManagers;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {

        if (bksFile == null || password == null) {
            return null;
        }

        try {
            KeyStore keyStore = KeyStore.getInstance("BKS");
            keyStore.load(bksFile, password.toCharArray());

            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm
                    ());
            keyManagerFactory.init(keyStore, password.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static X509TrustManager chooseX509TrustManager(TrustManager[] trustManagers) {
        for (TrustManager trustManager : trustManagers) {
            if (trustManager instanceof X509TrustManager) {
                Log.i("aa","找到了"+((X509TrustManager) trustManager).getAcceptedIssuers());
                return (X509TrustManager) trustManager;
            }
        }
        return null;
    }

    private static class DefaultTrustManager implements X509TrustManager {

        private X509TrustManager allX509TrustManager;
        private X509TrustManager localTrustManager;

        public DefaultTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException,
                KeyStoreException {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory
                    .getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            allX509TrustManager = chooseX509TrustManager(trustManagerFactory.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 {
                allX509TrustManager.checkServerTrusted(chain, authType);
            } catch (CertificateException e) {
                e.printStackTrace();
                try {
                    localTrustManager.checkServerTrusted(chain, authType);
                } catch (CertificateException e1) {
                    e1.printStackTrace();
                }
            }
        }

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

    /**
     * 获取Https的证书
     * @param context Activity（fragment）的上下文
     * @return SSL的上下文对象
     */
    public static SSLContext getSSLContext(Context context) {
        CertificateFactory certificateFactory = null;
        InputStream inputStream = null;
        Certificate cer = null;
        KeyStore keystore = null;
        TrustManagerFactory trustManagerFactory = null;
        try {

//            certificateFactory = CertificateFactory.getInstance("X.509");
//            inputStream = context.getAssets().open("baidu.crt");//这里导入SSL证书文件
//
//            try {
//                //读取证书
//                cer = certificateFactory.generateCertificate(inputStream);
//            } finally {
//                inputStream.close();
//            }
//            //创建一个证书库，并将证书导入证书库
//            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
//            keystore.load(null,null); //双向验证时使用
//            keystore.setCertificateEntry("trust", cer);
//
//            // 实例化信任库
//            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//            // 初始化信任库
//            trustManagerFactory.init(keystore);
//
            SSLContext s_sSLContext = SSLContext.getInstance("TLS");
//            s_sSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

            //信任所有证书 （官方不推荐使用）
            s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {
				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
				@Override
				public void checkServerTrusted(X509Certificate[] arg0, String arg1)
						throws CertificateException {
				}
				@Override
				public void checkClientTrusted(X509Certificate[] arg0, String arg1)
						throws CertificateException {
				}
			}}, new SecureRandom());
            return s_sSLContext;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static RequestParams httParams(String url){
        RequestParams params = new RequestParams(Constant.HTTP_URL+"/"+url);
        params.addHeader("Content-Type", "application/json;charset=utf-8");
        if(!StringUtils.isEmpty(Constant.ACCESS_TOKEN)){
            params.addHeader("Authorization", "Bearer "+Constant.ACCESS_TOKEN);
        }
        params.setConnectTimeout(15000);
        params.setReadTimeout(15000);
        params.setAsJsonContent(true);
        return params;
    }

    public static void parserError(Activity activity, Throwable ex){
        try {
            if(ex instanceof SocketTimeoutException){
                ToastUtils.showToast(activity, "请求超时，请检查网络");
                return;
            }
            String exStr = ex.toString();
            int strIndex = exStr.indexOf("result:");
            String result = exStr.substring(strIndex+7).trim();
            JSONObject object = new JSONObject(result);
            int error_code = 0;
            if(object.has("status")) {
                error_code = object.getInt("status");
            }
            if(error_code == 401 || exStr.contains("请求未授权")){
                try {
                    EventMessage message = new EventMessage(1, "退出");
                    EventBus.getDefault().post(message);
                }catch (Exception e){
                    e.printStackTrace();
                }
                new Handler().postDelayed(activity::finish, 300);
            }
            else if(object.has("error")) {
                ToastUtils.showToast(activity, object.getString("error"));
            }
            else if(object.has("message")) {
                ToastUtils.showToast(activity, object.getString("message"));
            }else if(object.has("msg")) {
                ToastUtils.showToast(activity, object.getString("msg"));
            }
            mylog.error("请求异常：", ex);
        }catch (Exception e){
            e.printStackTrace();
            mylog.error(e.toString());
        }
    }
}