package kz.com.aman.kassa.bank.builders;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import ru.m4bank.mpos.service.network.retrofit.SSLConfiguration;

public class SslConfigurationBuilder {
    public static SSLConfiguration buildAllTrustConfiguration(String serverAddress) {
        X509TrustManager[] trustManager = getTrustManagers();
        return new SSLConfiguration.Builder()
                .trustManager(trustManager[0])
                .hostnameVerifier(getHostnameVerifier(serverAddress))
                .socketFactory(getSSLSocketFactory(trustManager))
                .build();
    }

    private static HostnameVerifier getHostnameVerifier(String serverUrl) {
        return (hostname, session) -> true;
    }

    private static X509TrustManager[] getTrustManagers() {
        return new X509TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
        }};
    }

    private static SSLSocketFactory getSSLSocketFactory(X509TrustManager[] trustManager) {
        try {
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManager, new java.security.SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            return null;
        }
    }
}
