package ru.yandex.qe.http.certificates;

import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

import org.apache.commons.io.IOUtils;

import static com.google.common.base.Throwables.propagate;

/**
 * @author rurikk
 */
public class KeyManagersProvider {
    private PrivateKey key;
    private X509Certificate cert;

    public KeyManagersProvider(PrivateKey key, X509Certificate cert) {
        this.key = key;
        this.cert = cert;
    }

    public KeyManagersProvider(String privateKeyPem, String certificatePem) {
        this(PemParser.parseRsa(privateKeyPem), PemParser.parseX509(certificatePem));
    }

    public KeyManagersProvider(File privateKeyPem, File certificatePem) {
        this(read(privateKeyPem), read(certificatePem));
    }

    private static String read(File file) {
        try {
            return IOUtils.toString(file.toURI());
        } catch (IOException e) {
            throw propagate(e);
        }
    }

    public KeyManager[] getKeyManagers() throws Exception {
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, "".toCharArray());
        keyStore.setKeyEntry("key", key, "".toCharArray(), new Certificate[]{cert});
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "".toCharArray());
        return kmf.getKeyManagers();
    }

    public SSLContext buildContext() {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(
                    getKeyManagers(),
                    TrustManagersProvider.getInstance().getTrustManagers(),
                    null);
            return context;
        } catch (Exception e) {
            throw propagate(e);
        }
    }
}
