package com.wrox.algorithms.ssearch;

import junit.framework.TestCase;

public abstract class AbstractStringSearcherTest extends TestCase {
    protected abstract StringSearcher createSearcher(CharSequence pattern);


    public void testNotFoundInAnEmptyText() {
        StringSearcher searcher = createSearcher("I TAK MNIE TAM NIE MA");

        assertNull(searcher.search("", 0));
    }


    public void testFindAtTheStart() {
        String text = "Znajdź mnie na początku";
        String pattern = "Znajdź";

        StringSearcher searcher = createSearcher(pattern);

        StringMatch match = searcher.search(text, 0);
        assertNotNull(match);
        assertEquals(text, match.getText());
        assertEquals(pattern, match.getPattern());
        assertEquals(0, match.getIndex());

        assertNull(searcher.search(text, match.getIndex() + 1));
    }


    public void testFindAtTheEnd() {
        String text = "Znajdź mnie na końcu";
        String pattern = "końcu";

        StringSearcher searcher = createSearcher(pattern);

        StringMatch match = searcher.search(text, 0);
        assertNotNull(match);
        assertEquals(text, match.getText());
        assertEquals(pattern, match.getPattern());
        assertEquals(15 , match.getIndex());

        assertNull(searcher.search(text, match.getIndex() + 1));
    }


    public void testFindInTheMiddle() {
        String text = "Jestem gdzieś pośrodku tego łańcucha";
        String pattern = "pośrodku";

        StringSearcher searcher = createSearcher(pattern);

        StringMatch match = searcher.search(text, 0);
        assertNotNull(match);
        assertEquals(text, match.getText());
        assertEquals(pattern, match.getPattern());
        assertEquals(14, match.getIndex());

        assertNull(searcher.search(text, match.getIndex() + 1));
    }


    public void testFindOverlapping() {
        String text = "abcdefffff-fedcba";
        String pattern = "fff";

        StringSearcher searcher = createSearcher(pattern);

        StringMatch match = searcher.search(text, 0);
        assertNotNull(match);
        assertEquals(text, match.getText());
        assertEquals(pattern, match.getPattern());
        assertEquals(5, match.getIndex());

        match = searcher.search(text, match.getIndex() + 1);
        assertNotNull(match);
        assertEquals(text, match.getText());
        assertEquals(pattern, match.getPattern());
        assertEquals(6, match.getIndex());

        match = searcher.search(text, match.getIndex() + 1);
        assertNotNull(match);
        assertEquals(text, match.getText());
        assertEquals(pattern, match.getPattern());
        assertEquals(7, match.getIndex());

        assertNull(searcher.search(text, match.getIndex() + 1));
    }



}
