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

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.data.representatives.AgencyRepresentativeRole;
import ru.yandex.autotests.direct.web.objects.AccountWeb;
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.CheckBox;
import ru.yandex.qatools.htmlelements.element.TextBlock;
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.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;

/**
 * @author Roman Kuhta (kuhtich@yandex-team.ru)
 */

@NamedUrls({
        @NamedUrl(name = "modify.user.page", url = "/registered/main.pl?cmd=modifyUser&ulogin={1}")
})
@Name("Страница редактирования клиента в базе")
public class ModifyUserPage extends BasePageObject implements IWebFrom<AccountWeb> {

    @Name("Номер телефона")
    @FindBy(name = "phone")
    private TextInput phone;

    @Name("Кнопка Сохранить")
    @FindBy(css = "button.b-modify-user__save")
    private Button saveButton;

    @Name("Город")
    @FindBy(name = "city")
    private TextInput cityTextInput;

    @Name("Текст Страна")
    @FindBy(xpath = ".//div[ ./div[@class='b-modify-user__country']]")
    private TextBlock countryText;

    @Name("Текст Валюта оплаты")
    @FindBy(xpath = ".//div[ ./div[@class='b-modify-user__currency']]")
    private TextBlock currencyText;

    @Name("Чекбокс - Показывать тизер для первой помощи")
    @FindBy(xpath = ".//input[@name='show_fa_teaser']")
    private CheckBoxBEM showFirstHelpTizerCheckBox;

    @Name("Кнопка продолжить")
    @FindBy(xpath = ".//button[@type='submit' and not(contains(@class, 'p-common-error__cancel'))]")
    private Button continueButton;

    @Name("Логин")
    @FindBy(css = "div.b-modify-user__login")
    private WebElement login;

    @Name("Роль")
    @FindBy(css = "div.b-modify-user__agency-role")
    private WebElement role;

    @Name("Название представителя")
    @FindBy(xpath = ".//input[@name='FIO']")
    private TextInput nameTextInput;

    @Name("E-mail")
    @FindBy(xpath = ".//input[@name='email']")
    private TextInput emailTextInput;

    @Name("Отображать контакты в клиентском интерфейсе")
    @FindBy(xpath = ".//input[@name='show_agency_contacts']")
    private CheckBoxBEM showContactsCheckBox;

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

    @Name("Отсылать копии писем главному представителю")
    @FindBy(xpath = ".//input[@name='agency_email_to_chief']")
    private CheckBoxBEM sendEmailToChiefRepresentativeCheckBox;

    @Name("Разрешить выставление счетов")
    @FindBy(xpath = ".//input[@name='agency_allow_pay']")
    private CheckBoxBEM allowBillCheckBox;

    @Name("Редактировать кампанию сабклиента")
    @FindBy(xpath = ".//input[contains(@name, 'isSuperSubClient')]")
    private CheckBoxBEM editCampaignCheckBox;

    @Name("Переносить средства с кампании на кампанию для сабклиента")
    @FindBy(xpath = ".//input[contains(@name, 'allowTransferMoney')]")
    private CheckBox transferFundsCheckBox;

    @Name("Управление кампаниями при помощи Exel для сабклиента")
    @FindBy(xpath = ".//input[contains(@name, 'allowImportXLS')]")
    private CheckBox manageCampaignsInExcelCheckBox;

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

    public void checkCountryText(Matcher matcher) {
        assertThat(countryText, matcher);
    }

    public void checkCurrencyText(Matcher matcher) {
        assertThat(currencyText, matcher);
    }

    public void clickOnContinueButton() {
        continueButton.click();
    }

    public void selectShowFirstHelpTizerCheckBox() {
        showFirstHelpTizerCheckBox.select();
    }

    public void setEditCampaignCheckBox(Boolean state) {
        setCheckboxState(editCampaignCheckBox, state);
    }

    public void setTransferFundsCheckBox(Boolean state) {
        setCheckboxState(transferFundsCheckBox, state);
    }

    public void setManageCampaignsInExcelCheckBox(Boolean state) {
        setCheckboxState(manageCampaignsInExcelCheckBox, state);
    }

    @Override
    public void fillParameters(AccountWeb accountWeb) {
        fillTextInput(nameTextInput, accountWeb.getName());
        fillTextInput(emailTextInput, accountWeb.getEmail());
        fillTextInput(phone, accountWeb.getPhone());
        setCheckboxState(showContactsCheckBox, accountWeb.getShowContactsAtClientInterface());
        fillSelect(languageSelect, accountWeb.getLanguage(), SelectInputMethod.BY_TEXT);
        setCheckboxState(sendEmailToChiefRepresentativeCheckBox,
                accountWeb.getSendEmailToChiefRepresentative());
        setCheckboxState(allowBillCheckBox, accountWeb.getAllowBill());
    }

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

    @Override
    public AccountWeb getFormFieldsAccording(AccountWeb expectedBean) {
        return inAccordanceWith(expectedBean).forNew(AccountWeb.class)
                .set("login", login, on(WebElement.class).getText())
                .set("agencyRepresentativeRole", role, on(WebElement.class).getText())
                .set("name", nameTextInput, on(TextInput.class).getText())
                .set("email", emailTextInput, on(TextInput.class).getText())
                .set("phone", phone, on(TextInput.class).getText())
                .set("showContactsAtClientInterface", showContactsCheckBox, on(CheckBox.class).isSelected())
                .set("language", languageSelect, on(SelectBEM.class).getSelectedText())
                .set("sendEmailToChiefRepresentative", sendEmailToChiefRepresentativeCheckBox,
                        on(CheckBox.class).isSelected())
                .set("allowBill", allowBillCheckBox, on(CheckBox.class).isSelected())
                .set("country", countryText, on(TextBlock.class).getText())
                .set("city", cityTextInput, on(TextInput.class).getText())
                .getActualBean();
    }
}
