package ru.yandex.autotests.direct.web.pages.banners.blocks.edit.bem.turbolandigs;

import java.util.List;

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

import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.qatools.allure.webdriver.pages.BasePageObject;
import ru.yandex.qatools.htmlelements.annotations.Name;
import ru.yandex.qatools.htmlelements.element.Button;

import static org.hamcrest.Matchers.not;
import static ru.yandex.autotests.direct.web.steps.CommonSteps.waitForElement;
import static ru.yandex.autotests.direct.web.util.WebElementsActions.isExists;
import static ru.yandex.qatools.htmlelements.matchers.WebElementMatchers.isDisplayed;

public class TurboLandingsPopup extends BasePageObject {

    @Name("Блоки превью турболендингов")
    @FindBy(css = ".nodes-list__item_view_column")
    private List<Button> turbolandingButtons;

    @Name("Выбрать")
    @FindBy(xpath = ".//span[@class='select-page__button-choose']/button[contains(@class, 'y-button_theme_action')]")
    private Button selectButton;

    @Name("Кнопка 'Добавить'")
    @FindBy(css = ".y-button_type_button.creation-button")
    private WebElement addTurboLanding;

    @Name("Кнопка 'Отмена' в попапе")
    @FindBy(xpath = ".//button[contains(@class, 'create-node__button')][2]")
    private WebElement cancelButton;

    public void selectTurboLandingFromGalleryByName(String name) {
        if (isExists(cancelButton)) {
            if (cancelButton.isDisplayed() && cancelButton.isEnabled()) {
                cancelButton.click();
            }
        }
        turbolandingButtons.stream().filter(b ->
                b.getWrappedElement().findElement(By.className("nodes-list__name")).getText().equals(name))
                .findFirst()
                .orElseThrow(() -> new DirectWebError("Не найден турболендинг с именем " + name))
                .click();
        selectButton.click();
        waitForElement(selectButton.getWrappedElement(), 5, not(isDisplayed()));
    }

    public void waitUntilRowsWillBeLoaded() {
        waitForElement(addTurboLanding, 10, isDisplayed());
    }
}
