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

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

import ru.yandex.autotests.direct.web.objects.autopayment.CardWeb;
import ru.yandex.qatools.allure.webdriver.pages.BasePageObject;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Button;
import ru.yandex.qatools.htmlelements.element.TextInput;

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

public class BindCardPage extends BasePageObject {

    @Name("Закрыть попап")
    @FindBy(css = ".popup__close")
    private WebElement popupClose;

    @Name("Ячейки ввода номера карты")
    @FindBy(xpath = ".//span[contains(@class, 'card_number-input')]//input")
    private TextInput cardNumberInput;

    @Name("Поле ввода месяца окончания карты")
    @FindBy(xpath = ".//input[@name = 'expiration_month']")
    private TextInput expirationMonth;

    @Name("Поле ввода года окончания карты")
    @FindBy(xpath = ".//input[@name = 'expiration_year']")
    private TextInput expirationYear;

    @Name("Поле ввода владельца карты")
    @FindBy(xpath = ".//input[@name = 'cardholder']")
    private TextInput cardholder;

    @Name("Поле ввода cvn")
    @FindBy(xpath = ".//input[@name = 'cvn']")
    private TextInput cvn;

    @Name("Кнопка привязать карту")
    @FindBy(xpath = ".//button[contains(@class, 'accent')]")
    private Button submit;

    @Name("Ответ привязки карты")
    @FindBy(xpath = ".//div[contains(@class 'binding-payment-response__content')]")
    private WebElement responseContent;

    @Name("Крутящаяся заглушка при загрузке")
    @FindBy(css = ".spinner")
    private WebElement spinLoader;

    public WebElement getResponseContent() {
        return responseContent;
    }

    private WebElement getSpinLoader () {
        return spinLoader;
    }

    public void waitForSpinLoader(Matcher<WebElement> matcher) {
        waitForElement(getSpinLoader(), 15, matcher);
    }

    public void fillParameters(CardWeb card) {
        fillCardNumber(card.getCardNumber());
        fillTextInput(expirationMonth, card.getExpirationMonth());
        fillTextInput(expirationYear, card.getExpirationYear());
        fillTextInput(cardholder, card.getCardOwner());
        fillTextInput(cvn, card.getCardCvc());
    }

    private void fillCardNumber(String cardNumber) {
        if (cardNumber == null) {
            return;
        }
        cardNumberInput.sendKeys(cardNumber);
    }

    public void clickSubmitButton() {
        submit.click();
    }

    public void closePopup() {
        popupClose.click();
    }
}
