package be.ehealth.technicalconnector.config.impl;

import be.ehealth.technicalconnector.config.Configuration;
import be.ehealth.technicalconnector.exception.TechnicalConnectorException;
import be.ehealth.technicalconnector.ws.ServiceFactory;
import be.ehealth.technicalconnector.ws.domain.GenericRequest;
import be.fgov.ehealth.technicalconnector.tests.junit.rule.ConfigurationFakeRule;
import be.fgov.ehealth.technicalconnector.tests.junit.rule.HttpServerStubRule;
import org.junit.*;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;

public class ConfigurationModuleSSLTest {

    @Rule
    public HttpServerStubRule server = new HttpServerStubRule();

    public ConfigurationModuleSSL module = new ConfigurationModuleSSL();

    @Rule
    public ConfigurationFakeRule configurationFakeRule = new ConfigurationFakeRule();

    @Before
    @After
    public void verify() throws Exception {
        HttpsURLConnection.setDefaultSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());

        try {
            call();
        } catch (Exception e) {
            if (e instanceof TechnicalConnectorException && e.getMessage().contains("unable to find valid certification path to requested target")) {
                return;
            }
        }
        Assert.fail("Certificate should be not trusted!");
    }

    @Test
    public void passThrough() throws Exception {
        Configuration config = configurationFakeRule.getConfiguration();
        config.setProperty("connector.configurationmodule.ssl.verifcation.flavour", "passthrough");

        module.init(config);
        call();
        module.unload();

    }

    @Test
    public void truststore() throws Exception {
        Configuration config = configurationFakeRule.getConfiguration();
        config.setProperty("connector.configurationmodule.ssl.verifcation.flavour", "truststore");
        config.setProperty("connector.configurationmodule.ssl.trustore.location", "/P12/local/truststore.jks");
        config.setProperty("connector.configurationmodule.ssl.trustore.password", "system");

        module.init(config);
        call();
        module.unload();
    }

    @Test
    @Deprecated
    public void customLegacyConfiguration() throws Exception {
        Configuration config = configurationFakeRule.getConfiguration();
        config.setProperty("KEYSTORE_DIR", "/P12/local/");
        config.setProperty("truststore_location", "truststore.jks");
        config.setProperty("truststore_password", "system");

        module.init(config);
        call();
        module.unload();
    }


    private void call() throws TechnicalConnectorException {
        GenericRequest genericRequest = new GenericRequest();

        genericRequest.setEndpoint(server.getEchoUrl().replaceAll("http:", "https:"));
        genericRequest.setPayload("<dummy>test</dummy>");

        ServiceFactory.getGenericWsSender().send(genericRequest);
    }

}