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

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

import ru.yandex.autotests.direct.web.data.RadioInputMethod;
import ru.yandex.autotests.direct.web.data.SelectInputMethod;
import ru.yandex.autotests.direct.web.data.autopayment.AutoPaymentTypeEnum;
import ru.yandex.autotests.direct.web.objects.autopayment.AutoPaymentWeb;
import ru.yandex.autotests.direct.web.pages.autopayment.blocks.ChoosePaymentSelectBlock;
import ru.yandex.autotests.direct.web.util.matchers.IsDisplayedMatcher;
import ru.yandex.autotests.direct.web.util.testinterfaces.Checkable;
import ru.yandex.autotests.direct.web.webelements.bem.CheckBoxBEM;
import ru.yandex.autotests.direct.web.webelements.bem.RadioBEM;
import ru.yandex.autotests.irt.testutils.allure.TestSteps;
import ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher;
import ru.yandex.qatools.allure.webdriver.annotations.NamedUrl;
import ru.yandex.qatools.allure.webdriver.annotations.NamedUrls;
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 org.hamcrest.MatcherAssert.assertThat;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillRadio;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillSelect;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.fillTextInput;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.setCheckboxState;
import static ru.yandex.autotests.irt.testutils.beans.BeanFieldsSetter.inAccordanceWith;


@NamedUrls({
        @NamedUrl(name = "client.autopayment", url = "/registered/main.pl?cmd=autopaySettings"),
        @NamedUrl(name = "client.autopayment.for", url = "/registered/main.pl?cmd=autopaySettings&ulogin={1}")
})
public class AutoPaymentPage extends BasePageObject implements Checkable<AutoPaymentWeb> {

    @Name("Чекбокс включения/отключения автопополнения")
    @FindBy(xpath = ".//span[contains(@class, 'autopay-settings__mode-checkbox')]//input")
    private CheckBoxBEM enableAutoPayment;

    @Name("Поле ввода остатка")
    @FindBy(xpath = ".//span[contains(@class, 'autopay-settings__remaining-sum')]//input")
    private TextInput remainingSum;

    @Name("Поле ввода пополнения")
    @FindBy(xpath = ".//span[contains(@class, 'autopay-settings__payment-sum')]//input")
    private TextInput paymentSum;

    @Name("Выбор способа оплаты")
    @FindBy(xpath = ".//input[@name = 'paymethod_type']")
    private RadioBEM choosePaymentType;

    @FindBy(xpath = "//div[contains(@class, 'autopay-settings__dropdown_type_yandex-moneys')]")
    private ChoosePaymentSelectBlock chooseYMBlock;

    @Name("Ссылка добавления карты")
    @FindBy(xpath = ".//span[contains(@class, 'autopay-settings__add-card')]")
    private WebElement addCardLink;

    @Name("Чек-бокс согласия с Офертой")
    @FindBy(xpath = ".//input[@name='accept']")
    private CheckBoxBEM acceptOfertaRadio;

    @Name("Ссылка на оферту")
    @FindBy(xpath = ".//span[contains(@class, 'p-autopay-settings__oferta-link')]")
    private WebElement ofertaLink;

    @Name("Кнопка сохранить автопополнение")
    @FindBy(xpath = ".//button[contains(@class, 'autopay-settings__save')]")
    private Button saveAutoPaymentButton;

    private WebElement getBindCardPopup() {
        return config.getDriver()
                .findElement(By.xpath("//iframe[contains(@src, 'cmd=ajaxGetBindingForm')]"));
    }

    public Boolean isEnableAutoPayment() {
        return enableAutoPayment.isSelected();
    }

    public String getRemainingSum() {
        return remainingSum.getText();
    }

    public String getPaymentSum() {
        return paymentSum.getText();
    }

    public WebElement getOfertaLink() {
        return ofertaLink;
    }

    public CheckBoxBEM getOfertaCheckBox() {
        return acceptOfertaRadio;
    }

    public AutoPaymentTypeEnum getAutoPaymentType() {
        return AutoPaymentTypeEnum.getEnumByValue(choosePaymentType.getSelectedValue());
    }

    public String getPaymentId() {
        String paymentId = null;
        switch (getAutoPaymentType()) {
            case YANDEX_MONEY:
                paymentId = chooseYMBlock.getSelectedCardId().replace("_", "-");
                break;
        }
        return paymentId;
    }

    public void clickShowAddCard() {
        addCardLink.click();
    }

    public void clickSaveAutoPayment() {
        saveAutoPaymentButton.click();
    }

    public void shouldSeeBindCardBlock(Matcher<WebElement> matcher) {
        TestSteps.assertThat("блок привязки карты соответствует ожиданию", getBindCardPopup(), matcher);
    }

    @Override
    public void fillParameters(AutoPaymentWeb bean) {
        setCheckboxState(enableAutoPayment, bean.isEnabled());
        if (bean.getPaymentType() != null) {
            fillRadio(choosePaymentType, bean.getPaymentType().getValue(), RadioInputMethod.BY_VALUE);
            switch (bean.getPaymentType()) {
                case YANDEX_MONEY:
                    fillSelect(chooseYMBlock, bean.getPaymentId(), SelectInputMethod.BY_VALUE);
                    break;
            }
        }
        if (IsDisplayedMatcher.isDisplayed().matches(acceptOfertaRadio)) {
            acceptOfertaRadio.select();
        }
        fillTextInput(remainingSum, bean.getRemainingSum());
        fillTextInput(paymentSum, bean.getPaymentSum());
    }

    @Override
    public void checkParameters(BeanDifferMatcher<AutoPaymentWeb> matcher) {
        assertThat("неверные параметры автопополнения",
                getBean(matcher.getExpectedBean()), matcher);
    }

    @Override
    public AutoPaymentWeb getBean(AutoPaymentWeb expectedBean) {
        return inAccordanceWith(expectedBean).forNew(AutoPaymentWeb.class)
                .set("enabled", this, AutoPaymentPage::isEnableAutoPayment)
                .set("remainingSum", this, AutoPaymentPage::getRemainingSum)
                .set("paymentSum", this, AutoPaymentPage::getPaymentSum)
                .set("paymentType", this, AutoPaymentPage::getAutoPaymentType)
                .set("paymentId", this, AutoPaymentPage::getPaymentId)
                .getActualBean();
    }
}
