package ru.yandex.autotests.direct.web.pages.campaigns.blocks.bem;


import org.openqa.selenium.support.FindBy;

import ru.yandex.autotests.direct.web.objects.campaigns.parameters.EmailNotificationInfoWeb;
import ru.yandex.autotests.direct.web.pages.ExtendedHtmlElement;
import ru.yandex.autotests.direct.web.util.WebElementsActions;
import ru.yandex.autotests.direct.web.util.testinterfaces.IWebFrom;
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.Button;
import ru.yandex.qatools.htmlelements.element.TextInput;

import static ch.lambdaj.Lambda.on;
import static org.hamcrest.MatcherAssert.assertThat;
import static ru.yandex.autotests.direct.utils.matchers.BeanEquals.beanEquals;
import static ru.yandex.autotests.direct.web.steps.BackendSteps.toBoolean;
import static ru.yandex.autotests.direct.web.steps.BackendSteps.toDirectApiBooleanString;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.setCheckboxState;
import static ru.yandex.autotests.direct.web.util.beanutils.BeanFieldsSetter.inAccordanceWith;

/**
 * Created by shmykov on 19.06.14.
 */
@Name("Попап email уведомлений")
@FindBy(xpath = ".//div[contains(@class, 'popup_visibility_visible')]" +
        "[.//div[contains(@class, 'b-email-notification')]]")
public class EmailNotificationsPopupBlock extends ExtendedHtmlElement implements IWebFrom<EmailNotificationInfoWeb> {

    @Name("Список выбора email")
    @FindBy(css = ".b-email-select__select select")
    private SelectBEM email;

    @Name("Кнопка Добавить email")
    @FindBy(css = ".b-email-select__add-btn")
    private Button addEmailButton;

    @Name("Поле ввода нового emaila")
    @FindBy(css = ".b-email-select__email input")
    private TextInput newEmailInput;

    @Name("Кнопка сохранения нового адреса")
    @FindBy(css = ".b-email-select__ok")
    private Button saveNewEmailButton;

    @Name("Поле для ввода Уведомлять при уровне остатка средств на кампании")
    @FindBy(css = "span.b-email-notification__email-input input.input__control")
    private NumericInput moneyWarningValue;

    @Name("Предупреждения о смене позиции, уточнении и фразах с низким CTR")
    @FindBy(css = ".b-email-notification__send-warn input")
    private CheckBoxBEM sendWarn;

    @Name("Список Переодичность отправки")
    @FindBy(css = ".b-email-notification__warn-interval select")
    private SelectBEM warnPlaceInterval;

    @Name("Уведомления о готовности Excel-отчетов ")
    @FindBy(xpath = ".//span[contains(@data-bem, '\"name\":\"offlineStatNotice\"')]//span/input")
    private CheckBoxBEM sendAccNews;

    @Name("Кнопка 'Сохранить'")
    @FindBy(xpath = ".//button[contains(@class, 'b-campaign-email-notifications__accept-button')]")
    private Button saveButton;

    @Name("Кнопка 'Отмена'")
    @FindBy(xpath = ".//button[contains(@class, 'b-campaign-email-notifications__decline-button')]")
    private Button cancelButton;


    public void fillEmail(String email) {
        if (email == null) {
            return;
        }
        if (!this.email.getSelectedText().equals(email)) {
            addEmailButton.click();
            new WebElementsActions(config).fillTextInputWithClickAndEvents(newEmailInput, email);
            saveNewEmailButton.click();
        }
    }

    private void fillWarnPlaceInterval(Integer value) {
        if (value == 0) {
            this.sendWarn.deselect();
            return;
        }
        this.sendWarn.select();
        this.warnPlaceInterval.selectByValue(String.valueOf(value));
    }

    public String getEmail() {
        return email.getSelectedText();
    }

    public String getSendWarn() {
        return toDirectApiBooleanString(sendWarn.isSelected());
    }

    public String getWarnPlaceInterval() {
        return warnPlaceInterval.getFirstSelectedOption().getAttribute("value");
    }

    public String getSendAccNews() {
        return toDirectApiBooleanString(sendAccNews.isSelected());
    }

    public void clickCancel() {
        cancelButton.click();
    }

    @Override
    public void fillParameters(EmailNotificationInfoWeb info) {
        fillEmail(info.getEmail());
        if (info.getMoneyWarningValue() != null) {
            new WebElementsActions(config).setNumericValue(moneyWarningValue, info.getMoneyWarningValue());
        }
        if (info.getWarnPlaceInterval() != null) {
            fillWarnPlaceInterval(info.getWarnPlaceInterval());
        }
        setCheckboxState(sendAccNews, toBoolean(info.getSendAccNews()));
        this.saveButton.click();
    }

    @Override
    public void checkParameters(EmailNotificationInfoWeb info) {
        assertThat("неверные параметры нотификаций", getFormFieldsAccording(info), beanEquals(info));
    }

    @Override
    public EmailNotificationInfoWeb getFormFieldsAccording(EmailNotificationInfoWeb expectedBean) {
        return inAccordanceWith(expectedBean).forNew(EmailNotificationInfoWeb.class)
                .set("email", this, on(EmailNotificationsPopupBlock.class).getEmail())
                .set("moneyWarningValue", moneyWarningValue, on(NumericInput.class).getValue())
                .set("sendWarn", this, on(EmailNotificationsPopupBlock.class).getSendWarn())
                .set("warnPlaceInterval", this, on(EmailNotificationsPopupBlock.class).getWarnPlaceInterval())
                .set("sendAccNews", this, on(EmailNotificationsPopupBlock.class).getSendAccNews())
                .getActualBean();
    }
}
