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

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.openqa.selenium.WebElement;

import ru.yandex.qatools.htmlelements.element.Radio;

/**
 * Created with IntelliJ IDEA.
 * User: alexey-n
 * Date: 11.10.13
 * Time: 12:24
 * To change this template use File | Settings | File Templates.
 */
public class HasRadioButton extends TypeSafeMatcher<Radio> {
    private final Matcher<WebElement> buttonMatcher;
    private String value;

    public HasRadioButton(String value, Matcher<WebElement> buttonMatcher) {
        this.buttonMatcher = buttonMatcher;
        this.value = value;
    }

    @Override
    protected boolean matchesSafely(Radio radio) {
        for (WebElement button : radio.getButtons()) {
            if (button.getAttribute("value").equals(value)) {
                return buttonMatcher.matches(button);
            }
        }
        return false;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText(" radio button '" + value + "' ").appendDescriptionOf(buttonMatcher);
    }

    @Override
    protected void describeMismatchSafely(Radio radio, Description mismatchDescription) {

        for (WebElement button : radio.getButtons()) {
            if (button.getAttribute("value").equals(value)) {
                mismatchDescription.
                        appendText(" button of ").
                        appendValue(radio).
                        appendText(" was ");
                buttonMatcher.describeMismatch(button, mismatchDescription);
                return;
            }
        }
        mismatchDescription.appendText(" button with value ").appendValue(value)
                .appendText(" not finded ");
    }

    @Factory
    public static Matcher<Radio> hasRadioButton(final String value, final Matcher<WebElement> buttonMatcher) {
        return new HasRadioButton(value, buttonMatcher);
    }
}

