package com.atlassian.stash.internal.logback.pattern;

import ch.qos.logback.classic.spi.ThrowableProxy;
import com.atlassian.bitbucket.hamcrest.RegexMatcher;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;

import java.sql.SQLException;
import java.util.regex.Pattern;

import static org.junit.Assert.assertThat;

public class EnhancedThrowableConverterTest {

    private final EnhancedThrowableConverter converter = new EnhancedThrowableConverter();

    @Before
    public void setup() {
        converter.start();
    }

    @Test
    public void testCauseIsExtracted() {
        Exception cause = new RuntimeException("test-cause");
        Exception e = new RuntimeException("test-one", cause);

        String s = convert(e);

        assertMessageWithTrace(s, "test-cause");
        assertMessageWithTrace(s, "test-one");
    }

    @Test
    public void testNextSqlExceptionsAreExtracted() {
        Exception cause = new RuntimeException("test-cause");
        SQLException e1 = new SQLException("test-one", cause);
        SQLException e2 = new SQLException("test-two");
        SQLException e3 = new SQLException("test-three");
        e1.setNextException(e2);
        e2.setNextException(e3);

        String s = convert(e1);
        assertMessageWithTrace(s, "test-one");
        assertMessageWithTrace(s, "test-two");
        assertMessageWithTrace(s, "test-three");
        assertMessageWithTrace(s, "test-cause");
    }

    private String convert(Throwable throwable) {
        return converter.throwableProxyToString(new ThrowableProxy(throwable));
    }

    private void assertMessageWithTrace(String fullText, String expectedMessage) {
        Matcher<String> matcher = RegexMatcher.matchesRegex(Pattern.quote(expectedMessage) +
                "\\s+at com\\.atlassian\\.");
        assertThat(fullText, matcher);
    }
}
