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

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

import ru.yandex.autotests.direct.utils.strategy.objects.StrategyInfoWeb;
import ru.yandex.autotests.direct.web.pages.ExtendedHtmlElement;
import ru.yandex.autotests.direct.web.util.JavaScriptActions;
import ru.yandex.autotests.direct.web.util.WebElementsActions;
import ru.yandex.autotests.direct.web.webelements.NumericInput;
import ru.yandex.autotests.direct.web.webelements.bem.CheckBoxBEM;
import ru.yandex.autotests.direct.web.webelements.bem.SelectBEM;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Select;
import ru.yandex.qatools.htmlelements.matchers.WebElementMatchers;

import static ch.lambdaj.Lambda.on;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static ru.yandex.autotests.direct.utils.matchers.BeanEquals.beanEquals;
import static ru.yandex.autotests.direct.web.util.OperationSystemUtils.sleep;
import static ru.yandex.autotests.direct.web.util.beanutils.BeanFieldsSetter.inAccordanceWith;

@Name("Настройки опции дневной бюджет")
@FindBy(css = ".b-strategy2-settings__day-budget")
public class DayBudgetBemBlock extends ExtendedHtmlElement {

    @Name("Чекбокс активации дневного бюджета")
    @FindBy(xpath = ".//span[contains(@data-bem, '\"name\":\"dayBudgetEnabled\"')]//input")
    protected CheckBoxBEM enableDayBudgetCheckBox;

    @Name("Хелп бокс с информацией о дневном бюджете")
    @FindBy(xpath = ".//span[contains(@class, 'b-help-link')]")
    protected WebElement dayBudgetHelp;

    @Name("Сумма дневного бюджета")
    @FindBy(xpath = ".//span[contains(@data-bem, '\"name\":\"sum\"')]//input")
    protected NumericInput dayBudgetSum;

    @Name("Режим показа дневного бюджета")
    @FindBy(xpath = ".//select[@class='select__control']")
    protected SelectBEM dayBudgetShowsMode;

    @Name("Директовский алерт")
    @FindBy(xpath = "//div[contains(@class, 'popup_visibility_visible') and .//div[@class='b-confirm__message']]")
    private WebElement directAlert;

    @Name("Кнопка Ок в директовском алерте")
    @FindBy(xpath = "//div[contains(@class, 'popup_visibility_visible')" +
            " and .//div[@class='b-confirm__message']]//button[contains(@class, 'b-confirm__yes')]")
    private WebElement directAlertButton;

    public WebElement getDayBudgetHelp() {
        return dayBudgetHelp;
    }

    public Select getDayBudgetShowsMode() {
        return dayBudgetShowsMode;
    }

    public String getDayBudgetSumText() {
        if (dayBudgetSum == null) {
            return "";
        }
        return dayBudgetSum.getAttribute("value");
    }

    public StrategyInfoWeb.ShowMode getDayBudgetShowModeValue() {
        if (dayBudgetShowsMode.getFirstSelectedOption().getAttribute("value")
                .equals(StrategyInfoWeb.ShowMode.DEFAULT.name().toLowerCase())) {
            return StrategyInfoWeb.ShowMode.DEFAULT;
        }
        return StrategyInfoWeb.ShowMode.STRETCHED;
    }

    public void fillDayBudget(StrategyInfoWeb strategy) {
        if (strategy.getDayBudgetSum() != null) {
            enableDayBudgetCheckBox.select();
            new WebElementsActions(config).setNumericValue(dayBudgetSum
                    , Double.toString(strategy.getDayBudgetSum()));
            new JavaScriptActions(config).fireBlurEvent(dayBudgetSum.getWrappedElement());
        } else {
            enableDayBudgetCheckBox.deselect();
        }

        if (strategy.getDayBudgetShowMode() != null) {
            dayBudgetShowsMode.selectByValue(strategy.getDayBudgetShowMode().name().toLowerCase());
        }
        sleep(1000);
    }


    public void checkDayBudget(StrategyInfoWeb expectedBean) {
        assertTrue("Дневной бюджет не задан", enableDayBudgetCheckBox.isSelected());
        StrategyInfoWeb actualBean = inAccordanceWith(expectedBean)
                .forNew(StrategyInfoWeb.class)
                .set("dayBudgetSum", this, on(DayBudgetBemBlock.class).getDayBudgetSumText())
                .set("dayBudgetShowMode", this, on(DayBudgetBemBlock.class).getDayBudgetShowModeValue())
                .getActualBean();

        assertThat("параметры дневного бюджета отличаются от ожидаемых", expectedBean, beanEquals(actualBean));
    }

    public void acceptAlert(Matcher matcher) {
        MatcherAssert.assertThat("неверный текст алерта", directAlert.getText(), matcher);
        directAlertButton.click();
    }

    public boolean isAlertPresent() {
        return WebElementMatchers.isDisplayed().matches(directAlert);
    }

    public void checkDayBudgetAlertText(Matcher<String> matcher) {
        String dayBudgetSumText = getDayBudgetSumText();
        dayBudgetSum.clear();
        if (!isAlertPresent()) {
            new WebElementsActions(config).setNumericValue(dayBudgetSum, dayBudgetSumText);
            new JavaScriptActions(config).fireBlurEvent(dayBudgetSum.getWrappedElement());
        }
        acceptAlert(matcher);
    }
}
