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

import java.util.Properties;

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 be.fgov.ehealth.technicalconnector.tests.junit.rule.callbacks.AssertSOAPQueryCallback;
import be.fgov.ehealth.technicalconnector.tests.utils.PortUtils;

/**
 * @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;
    }
}