package ru.yandex.autotests.direct.web.util.matchers;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

/**
 * User: alexey-n
 * Date: 17.07.13
 * Time: 15:04
 */
public class WithReplace extends TypeSafeMatcher<String> {

    protected final Matcher<String> stringMatcher;
    protected final String regex;
    protected final String replacement;

    public WithReplace(String regex, String replacement, Matcher<String> stringMatcher) {
        this.stringMatcher = stringMatcher;
        this.regex = regex;
        this.replacement = replacement;
    }

    @Override
    public boolean matchesSafely(String item) {
        return stringMatcher.matches(item.replaceAll(regex, replacement));
    }

    public void describeTo(Description description) {
        description.appendDescriptionOf(stringMatcher);
    }

    @Override
    protected void describeMismatchSafely(String item, Description mismatchDescription) {
        mismatchDescription.appendText("text was").appendValue(item.replaceAll(regex, replacement));
    }

    @Factory
    public static Matcher<String> withReplace(final String regex, final String replacement,
                                              final Matcher<String> stringMatcher) {
        return new WithReplace(regex, replacement, stringMatcher);
    }
}
