package de.duehl.basics.regex;

/*
 * Copyright 2024 Christian Dühl. All rights reserved.
 *
 * This program is free software. You can redistribute it and/or
 * modify it under the same terms as perl:
 *
 * general:  http://dev.perl.org/licenses/
 * GPL:      http://dev.perl.org/licenses/gpl1.html
 * artistic: http://dev.perl.org/licenses/artistic.html
 */

import static org.junit.Assert.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

import de.duehl.basics.collections.CollectionsHelper;

public class RegexHelperTest {

    @Test
    public void buildOrRegexFromList() {
        List<String> things = CollectionsHelper.buildListFrom("aaa", "bbb", "ccc");
        String expected = "(?:"
                + "\\Qaaa\\E|"
                + "\\Qbbb\\E|"
                + "\\Qccc\\E)";
        String actual = RegexHelper.buildOrRegexFromList(things);
        assertEquals(expected, actual);
    }

    @Test
    public void buildNotQuotingOrRegexFromList() {
        List<String> things = CollectionsHelper.buildListFrom("Ba.*ne", "Bir?ne", "[CZ]itrone");
        String expected = "(?:"
                + "Ba.*ne|"
                + "Bir?ne|"
                + "[CZ]itrone)";
        String actual = RegexHelper.buildNotQuotingOrRegexFromList(things);
        assertEquals(expected, actual);
    }

    @Test
    public void createQuotedList() {
        List<String> things = CollectionsHelper.buildListFrom("aaa", "bbb", "ccc");
        List<String> actual = RegexHelper.createQuotedList(things);
        List<String> expected = CollectionsHelper.buildListFrom(
                "\\Qaaa\\E",
                "\\Qbbb\\E",
                "\\Qccc\\E");
        assertEquals(expected, actual);
    }

    @Test
    public void compileListOfRegexes() {
        List<String> regexes = CollectionsHelper.buildListFrom("Apf.l", "[Bb]irne");
        List<Pattern> patterns = RegexHelper.compileListOfRegexes(regexes);

        assertEquals(regexes.size(), patterns.size());

        String sentence = "Auf dem Tisch liegen ein Apfel und eine Birne.";
        boolean allFound = true;
        for (Pattern pattern : patterns) {
            Matcher matcher = pattern.matcher(sentence);
            if (!matcher.find()) {
                allFound = false;
            }
        }
        assertTrue(allFound);
    }

}
