package cd.casic.framework.commons.util.http;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import cd.casic.framework.commons.exception.ServiceException;
import lombok.SneakyThrows;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * @author liubin
 * @date 2023/10/11 14:02
 * @description
 */
public class OkhttpUtils {

    private static final long connectTimeout = 5L;
    private static final long readTimeout = 30L;
    private static final long writeTimeout = 30L;

    private static final TrustManager[] trustAnyCerts = new TrustManager[]{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];
        }
    }};

    private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(connectTimeout, TimeUnit.SECONDS)
            .readTimeout(readTimeout, TimeUnit.MINUTES)
            .writeTimeout(writeTimeout, TimeUnit.MINUTES)
            .sslSocketFactory(anySslSocketFactory(), (X509TrustManager) trustAnyCerts[0])
            .hostnameVerifier((s, sslSession) -> true)
            .build();

    private static SSLSocketFactory anySslSocketFactory(){
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAnyCerts, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception ignore){
            throw new ServiceException();
        }
    }

    public static Response doHttp(Request request) {
        return doHttp(okHttpClient, request);
    }

    @SneakyThrows
    private static Response doHttp(OkHttpClient okHttpClient, Request request) {
        return okHttpClient.newCall(request).execute();
    }
}
