package be.ehealth.technicalconnector.handler;

import be.ehealth.technicalconnector.config.ConfigFactory;
import be.ehealth.technicalconnector.config.impl.ConfigurationFake;
import be.ehealth.technicalconnector.ws.impl.SOAPMessageContextImpl;
import be.fgov.ehealth.technicalconnector.tests.junit.rule.ConfigurationFakeRule;
import be.fgov.ehealth.technicalconnector.tests.junit.rule.LoggingRule;
import be.fgov.ehealth.technicalconnector.tests.junit.rule.RestoreSystemProperties;
import be.fgov.ehealth.technicalconnector.tests.utils.LoggingUtils;
import org.junit.*;
import org.junit.rules.TestRule;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.regex.Pattern;

import static org.junit.Assert.*;

public class FromHandlerTest {

    @Rule
    public ConfigurationFakeRule configurationFakeRule = new ConfigurationFakeRule();

    @Rule
    public final TestRule restoreSystemProperties = new RestoreSystemProperties();


    @ClassRule
    public static LoggingRule logging = LoggingRule.with().consoleAppender().build();

    @Test
    public void withoutProperty() throws Exception {
        String[] header = invoke();
        Assert.assertNull(header);
    }

    @Test
    public void withValidProperty() throws Exception {
        configurationFakeRule.setProperty("be.ehealth.technicalconnector.handler.mime-headers.from.value", "info@connector.be");

        String[] header = invoke();
        Assert.assertEquals(1, header.length);
        Assert.assertEquals("info@connector.be",header[0]);

    }

    @Test
    public void withInvalidProperty() throws Exception {
        configurationFakeRule.setProperty("be.ehealth.technicalconnector.handler.mime-headers.from.value", "info-connector.be");

        String[] header = invoke();
        Assert.assertNull(header);

    }

    @Test
    public void withValidPropertyWithCustomRegex() throws Exception {
        System.setProperty("be.ehealth.technicalconnector.handler.mime-headers.from.regex","[a-z-.]*");
        configurationFakeRule.setProperty("be.ehealth.technicalconnector.handler.mime-headers.from.value", "info-connector.be");

        String[] header = invoke();
        Assert.assertEquals(1, header.length);
        Assert.assertEquals("info-connector.be",header[0]);

    }


    private String[] invoke() throws SOAPException {
        MessageFactory mf = MessageFactory.newInstance();

        SOAPMessage soapMessage = mf.createMessage();
        SOAPMessageContext context = new SOAPMessageContextImpl(soapMessage);

        new FromHandler().handleOutbound(context);

        return context.getMessage().getMimeHeaders().getHeader("From");
    }

}