package ru.yandex.autotests.direct.web.pages;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.yandex.autotests.direct.web.util.helpers.URLParameterHelper;
import ru.yandex.autotests.passport.api.tools.captcha.CaptchaActions;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Button;
import ru.yandex.qatools.htmlelements.element.TextInput;
import ru.yandex.qatools.htmlelements.matchers.WebElementMatchers;

import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillTextInput;

/**
 * @author shmykov
 */
@FindBy(css = "div.b-ajax-captcha")
public class CaptchaPopupBlock extends ExtendedHtmlElement {

    @Name("Текст капчи")
    @FindBy(css = "img.b-ajax-captcha__img")
    private WebElement captchaText;

    @Name("Инпут капчи")
    @FindBy(css = "input")
    private TextInput captchaInput;

    @Name("Кнопка 'продолжить'")
    @FindBy(css = "button")
    private Button continueButton;

    public void fillCaptcha() {
        fillTextInput(captchaInput, CaptchaActions.getCaptchaAnswerByKey(URLParameterHelper.getUrlParameterByName(
                captchaText.getAttribute("src"), "key")));
    }

    public boolean isCaptchaDisplayed() {
        return WebElementMatchers.isDisplayed().matches(this);
    }

    public void fillIfDisplayed() {
        if (isCaptchaDisplayed()) {
            fillCaptcha();
            clickContinue();
        }
    }

    public void clickContinue() {
        continueButton.click();
    }
}
