package com.atlassian.bitbucket.util;

import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class PatternIterableTest {

    @Parameterized.Parameters
    public static Collection<Object[]> data() throws Exception {
        return ImmutableList.<Object[]>builder()
                .add(new Object[]{Pattern.compile("\\d+"), "abc 123 def 456 42", PatternIterable.group(0), ImmutableList.of("123", "456", "42")})
                .add(new Object[]{Pattern.compile("\\d+"), "abc 123 def 456 ghi-42", PatternIterable.group(0), ImmutableList.of("123", "456", "42")})
                .add(new Object[]{Pattern.compile("[a-z]+"), "abc 123 def 456 ghi-42", PatternIterable.group(0), ImmutableList.of("abc", "def", "ghi")})
                .add(new Object[]{Pattern.compile("[a-zA-Z]+-\\d+"), "abc 123 def 456 ghi-42 JKL-84", PatternIterable.group(0), ImmutableList.of("ghi-42", "JKL-84")})
                .add(new Object[]{Pattern.compile("[a-zA-Z]+-(\\d+)"), "abc 123 def 456 ghi-42 JKL-84", PatternIterable.group(0), ImmutableList.of("ghi-42", "JKL-84")})
                .add(new Object[]{Pattern.compile("[a-zA-Z]+-(\\d+)"), "abc 123 def 456 ghi-42 JKL-84", PatternIterable.group(1), ImmutableList.of("42", "84")})
                .build();
    }

    private final Pattern pattern;
    private final String text;
    private final Function<MatchResult, String> group;
    private final List<String> expected;

    public PatternIterableTest(Pattern pattern, String text, Function<MatchResult, String> group, List<String> expected) {
        this.pattern = pattern;
        this.text = text;
        this.group = group;
        this.expected = expected;
    }

    @Test
    public void testMatches() throws Exception {
        Iterable<String> iterable = new PatternIterable<String>(pattern, text, group);
        assertEquals(String.format("for pattern '%s', text '%s' and group '%s'", pattern, text, group),
                expected, ImmutableList.copyOf(iterable));
    }
}
