/*
 * Copyright (c) eHealth
 */
package be.fgov.ehealth.technicalconnector.tests.junit.rule;

import be.fgov.ehealth.technicalconnector.tests.junit.rule.callbacks.AssertSOAPQueryCallback;
import be.fgov.ehealth.technicalconnector.tests.utils.PortUtils;
import org.junit.rules.ExternalResource;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.mock.action.ExpectationCallback;
import org.mockserver.model.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * @author EHP
 */
public class MockServerRule extends ExternalResource {

    private static final Logger LOG = LoggerFactory.getLogger(AssertSOAPQueryCallback.class);

    private int port;

    private ClientAndServer server;
    
    private Properties sessionProperties = new Properties();

    public MockServerRule() {
        this(PortUtils.getFreePort());
    }

    public MockServerRule(int portNumber) {
        port = portNumber;
        server = ClientAndServer.startClientAndServer(port);
        LOG.debug("[MOCKSERVER] Server starter on port : " + port);
    }

    @Override
    protected void before() {
    }

    @Override
    protected void after() {
        server.stop();
    }

    public MockServerRule addEndpointCallback(String propertyToReplace, String pathToUse, ExpectationCallback callback) {
        LOG.debug("[MOCKSERVER] Callback added on : " + "http://127.0.0.1:" + port + pathToUse);
        sessionProperties.put(propertyToReplace, "http://127.0.0.1:" + port + pathToUse);
        server.when(HttpRequest.request().withPath(pathToUse)).callback(callback);
        return this;
    }

    public Properties getSessionProperties() {
        return sessionProperties;
    }
}