package it.com.atlassian.stash.rest.webhook;

import com.atlassian.bitbucket.test.rest.server.stub.webhook.StubWebHookSink;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;

import java.util.function.Supplier;
import java.util.stream.Collectors;

import static com.atlassian.bitbucket.test.rest.server.stub.mirror.StubMirror.DEFAULT_ENSURE_TIMEOUT;
import static com.atlassian.bitbucket.test.rest.server.stub.mirror.StubMirror.DEFAULT_EXPECTED_TIMEOUT;
import static org.junit.Assert.fail;

public class WebHookCallbackHelper {
    public static void assertFalse(Supplier<String> msgSupplier, boolean condition) {
        if (condition) {
            fail(msgSupplier.get());
        }
    }

    public static void assertTrue(Supplier<String> msgSupplier, boolean condition) {
        if (!condition) {
            fail(msgSupplier.get());
        }
    }

    public static void assertWebHookCallbackArrivedOn(StubWebHookSink stubWebHookSink, String eventId, Supplier<Matcher<String>> matcherSupplier) {
        assertTrue(
                expectedEventMsg(stubWebHookSink, eventId),
                stubWebHookSink.waitForWebhookEventCallback(matcherSupplier.get(), DEFAULT_EXPECTED_TIMEOUT));
    }

    public static void assertWebHookCallbackDidntArrivedOn(StubWebHookSink stubWebHookSink) {
        assertFalse(
                unexpectedEventMsg(stubWebHookSink),
                stubWebHookSink.waitForWebhookEventCallback(Matchers.any(String.class), DEFAULT_ENSURE_TIMEOUT));

    }

    public static Supplier<String> expectedEventMsg(StubWebHookSink stubWebHookSink, String eventId) {
        return () -> String.format("%s web hook should have been received. Requests received:\n%s",
                eventId, stubWebHookSink.getRequests().stream()
                        .map(r -> "Path: " + r.left() + "\nBody:\n" + r.right() + "\n")
                        .collect(Collectors.joining("\n")));
    }

    public static Supplier<String> unexpectedEventMsg(StubWebHookSink stubWebHookSink) {
        return () -> String.format("Web hooks should not have been received. Requests received:\n%s",
                stubWebHookSink.getRequests().stream()
                        .map(r -> "Path: " + r.left() + "\nBody:\n" + r.right() + "\n")
                        .collect(Collectors.joining("\n")));
    }
}
