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

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.hamcrest.Matcher;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.yandex.autotests.direct.web.data.SelectInputMethod;
import ru.yandex.autotests.direct.web.objects.AccountWeb;
import ru.yandex.autotests.direct.web.pages.campaigns.blocks.bem.MetrikaCountersPopupBlock;
import ru.yandex.autotests.direct.web.pages.users.blocks.AddEmailPopupBlock;
import ru.yandex.autotests.direct.web.util.testinterfaces.IWebFrom;
import ru.yandex.autotests.direct.web.webelements.bem.CheckBoxBEM;
import ru.yandex.autotests.direct.web.webelements.bem.SelectBEM;
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 ru.yandex.qatools.htmlelements.matchers.MatcherDecorators;
import ru.yandex.qatools.htmlelements.matchers.WebElementMatchers;

import static ch.lambdaj.Lambda.on;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
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.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.direct.web.util.beanutils.BeanFieldsSetter.inAccordanceWith;
import static ru.yandex.qatools.htmlelements.matchers.MatcherDecorators.timeoutHasExpired;


@Name("Страница настроек пользователя")
@NamedUrls({
        @NamedUrl(name = "self.settings", url = "/registered/main.pl?cmd=userSettings"),
        @NamedUrl(name = "user.settings", url = "/registered/main.pl?cmd=userSettings&ulogin={1}")
})
public class UserSettingsPage extends BasePageObject implements IWebFrom<AccountWeb> {

    private AddEmailPopupBlock addEmailPopup;

    private MetrikaCountersPopupBlock addMetrikaCountersPopup;

    @Name("Кнопка сохранить")
    @FindBy(xpath = ".//button[@type='submit']")
    protected Button saveButton;

    @Name("Чекбокс возможности редактирования дневного бюджета")
    @FindBy(xpath = ".//input[@name='can_use_day_budget']")
    private CheckBoxBEM dayBudgetCheckBox;

    @Name("ФИО клиента")
    @FindBy(xpath = ".//input[@name='fio']")
    private TextInput clientFIOInput;

    @Name("Телефон")
    @FindBy(xpath = ".//input[@name='phone']")
    private TextInput phoneTextInput;

    @Name("E-mail")
    @FindBy(xpath = ".//select[@name='email']")
    private SelectBEM emailSelect;

    @Name("Добавить новые E-mail")
    @FindBy(xpath = ".//button[contains(@class, 'b-user-settings__email-add-new')]")
    private Button addNewEmailButton;

    @Name("Добавить новые счётчики метрики")
    @FindBy(xpath = ".//button[contains(@class, 'b-metrika-counters-popup-adapter__opener')]")
    private Button addNewMetrikaCountersButton;

    @Name("Сохранённые счётчики метрики")
    @FindBy(xpath = ".//div[contains(@class, 'b-metrika-counters-popup-adapter__metrika-counters-string')]")
    private WebElement metrikaCounters;

    @Name("Получать рекомендации")
    @FindBy(xpath = ".//input[@name='news']")
    private CheckBoxBEM getRecommendationCheckBox;

    @Name("Язык уведомлений")
    @FindBy(xpath = ".//select[@name='email_lang']")
    private SelectBEM languageSelect;

    @Name("Показывать метки")
    @FindBy(xpath = ".//input[@name='tags_allowed']")
    private CheckBoxBEM showTagsCheckBox;

    @Name("Получать предупреждения о смене позиции, уточнении и фразах с низким CTR")
    @FindBy(xpath = ".//input[@name='warn']")
    private CheckBoxBEM getWarningsCheckBox;

    @Name("Получать уведомления по всем кампаниям")
    @FindBy(xpath = ".//input[@name='send_all_camp_letters']")
    private CheckBoxBEM getNotificationsCheckBox;

    @Name("Получать sms по всем кампаниям")
    @FindBy(xpath = ".//input[@name='send_all_camp_sms']")
    private CheckBoxBEM getSmsCheckBox;

    @Name("Показывать примечания к кампаниями")
    @FindBy(xpath = ".//input[@name='use_camp_description']")
    private CheckBoxBEM ShowCampaignDescriptionCheckBox;

    public CheckBoxBEM getDayBudgetCheckBox() {
        return dayBudgetCheckBox;
    }

    public void clickSaveButton() {
        saveButton.click();
    }

    public TextInput getClientFIOInput() {
        return clientFIOInput;
    }

    public void clickOnAddNewEmailButton() {
        addNewEmailButton.click();
    }

    public void fillEmailTextInput(String email) {
        addEmailPopup.fillEmailTextInput(email);
    }

    public void fillMetrikaCounters(String metrikaCounters) {
        if (metrikaCounters == null) {
            return;
        }
        addNewMetrikaCountersButton.click();
        addMetrikaCountersPopup.fillMetrikaCountersTextInput(metrikaCounters);
    }

    public void fillMetrikaCounters(List<Long> newMetrikaCounters) {
        String value = StringUtils.join(newMetrikaCounters, ", ");
        fillMetrikaCounters(value);
    }

    public void clickOnSaveEmailButton() {
        addEmailPopup.clickOnSaveButton();
    }


    public void fillMetrikaCountersSaveAndCheckNotVisible(List<Long> metrikaCounters) {
        fillMetrikaCountersSaveAndCheckPopup(metrikaCounters, not(WebElementMatchers.exists()));
    }

    public void fillMetrikaCountersSaveAndCheckVisible(List<Long> metrikaCounters) {
        fillMetrikaCountersSaveAndCheckPopup(metrikaCounters, WebElementMatchers.exists());
    }

    public void fillMetrikaCountersSaveAndCheckPopup(List<Long> metrikaCounters, Matcher<WebElement> matcher) {
        fillMetrikaCounters(metrikaCounters);
        addMetrikaCountersPopup.clickOnSaveButton();
        MatcherDecorators.should(matcher)
                .whileWaitingUntil(timeoutHasExpired(TimeUnit.SECONDS.toMillis(4))).matches(addMetrikaCountersPopup);
    }

    public void checkMetrikaValidationMessage(Matcher<WebElement> checkMatcher) {
        addMetrikaCountersPopup.checkValidationMessage(checkMatcher);
    }

    @Override
    public void fillParameters(AccountWeb accountWeb) {
        fillTextInput(clientFIOInput, accountWeb.getName());
        //валидация названия представителя
        sleep(3000);
        fillSelect(emailSelect, accountWeb.getEmail(), SelectInputMethod.BY_TEXT);
        fillMetrikaCounters(accountWeb.getMetrikaCounters());
        fillTextInput(phoneTextInput, accountWeb.getPhone());
        setCheckboxState(getRecommendationCheckBox, accountWeb.getRecommendations());
        setCheckboxState(showTagsCheckBox, accountWeb.getShowTags());
        fillSelect(languageSelect, accountWeb.getLanguage(), SelectInputMethod.BY_TEXT);
        setCheckboxState(getWarningsCheckBox, accountWeb.getWarnings());
        setCheckboxState(getNotificationsCheckBox, accountWeb.getNotifications());
        setCheckboxState(getSmsCheckBox, accountWeb.getSms());
        setCheckboxState(ShowCampaignDescriptionCheckBox, accountWeb.getDescriptions());
    }

    @Override
    public void checkParameters(AccountWeb expectedBean) {
        assertThat("неверные параметры бина ", getFormFieldsAccording(expectedBean),
                beanEquals(expectedBean));
    }

    @Override
    public AccountWeb getFormFieldsAccording(
            AccountWeb expectedBean)
    {
        AccountWeb accountWeb =
                inAccordanceWith(expectedBean).forNew(AccountWeb.class)
                        .set("name", clientFIOInput, on(TextInput.class).getText())
                        .set("email", emailSelect, on(SelectBEM.class).getSelectedText())
                        .set("metrikaCounters", metrikaCounters, on(WebElement.class).getText())
                        .set("phone", phoneTextInput, on(TextInput.class).getText())
                        .set("recommendations", getRecommendationCheckBox, on(CheckBoxBEM.class).isSelected())
                        .set("language", languageSelect, on(SelectBEM.class).getSelectedText())
                        .set("showTags", showTagsCheckBox, on(CheckBoxBEM.class).isSelected())
                        .set("warnings", getWarningsCheckBox, on(CheckBoxBEM.class).isSelected())
                        .set("notifications", getNotificationsCheckBox, on(CheckBoxBEM.class).isSelected())
                        .set("sms", getSmsCheckBox, on(CheckBoxBEM.class).isSelected())
                        .set("descriptions", ShowCampaignDescriptionCheckBox, on(CheckBoxBEM.class).isSelected())
                        .getActualBean();
        return accountWeb;
    }
}
