package ru.yandex.autotests.directapi.darkside.clients;

import ru.yandex.autotests.directapi.darkside.exceptions.DarkSideException;

import javax.net.ssl.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * Author xy6er
 * Date 06.11.14
 */
abstract public class CertificatesUtils {

    /**
     * A 'hacky' way of attempting to ignore a SSL certificate.
     */
    public static void ignoreCertificates() {
        try {
            IgnoreSSLTrustManager tm = new IgnoreSSLTrustManager();
            IgnoreSSLTrustManager[] trustAllCerts = {tm};

            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new AllowAllHostnameVerifier());
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new DarkSideException("Не удалось отключить проверку сертификатов для HttpsURLConnection", e);
        }
    }

    /**
     * Used to attempt to ignore SSL certificates.
     */
    public static final class IgnoreSSLTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

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

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

    /**
     * All trusting HostnameVerifier
     */
    public static final class AllowAllHostnameVerifier implements HostnameVerifier {

        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    }

}
