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

import java.util.List;

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

import ru.yandex.autotests.direct.web.pages.banners.blocks.edit.bem.imagebanners.blocks.CreativeFilterBlock;
import ru.yandex.autotests.direct.web.pages.banners.blocks.edit.bem.imagebanners.blocks.CreativePreviewBlock;
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 ru.yandex.qatools.htmlelements.element.TextInput;

import static org.hamcrest.core.IsNot.not;
import static ru.yandex.autotests.direct.web.steps.CommonSteps.waitForElement;
import static ru.yandex.autotests.direct.web.util.matchers.IsDisplayedMatcher.isDisplayed;

public class CreativesConstructorPage extends BasePageObject {
    @Name("Шаблоны креативов")
    @FindBy(xpath = ".//div[@class='list-item__inner']")
    private List<WebElement> creativeTemplates;

    @Name("Кнопка 'Создать баннеры'")
    @FindBy(xpath = ".//button[contains(@class, 'form__submit')]")
    private Button createBunnersButton;

    @Name("Кнопка 'Добавить баннеры в группу'")
    @FindBy(xpath = "(.//div[contains(@class, 'canvas-footer__footer-action')]//button)[1]")
    private Button addBannersToGroupButton;

    @Name("Кнопка 'Выбрать' размеры")
    @FindBy(xpath = ".//button[contains(@class, 'filter-list__pick-button')]")
    private Button chooseCreativesSizeButton;

    @Name("Кнопка 'Применить' выбранные размеры")
    @FindBy(xpath = "(.//div[@class='filter-list__actions']//button)[1]")
    private Button applyCreativesSizesButton;

    @Name("Спиннер")
    @FindBy(xpath = ".//div[contains(@class,'preloader__spin')]")
    private WebElement spinLoader;

    @Name("Блоки превью креативов на странице добавленных групп креативов")
    private List<CreativePreviewBlock> creativePreviewBlocks;

    @Name("Блоки креативов на странице создания нового креатива")
    private List<CreativeFilterBlock> creativeFiltersBlocks;

    @Name("Редактирование названия группы")
    @FindBy(xpath = ".//div[@class='creative-name__current-name']")
    private WebElement editGroupName;

    @Name("Поле ввода названия группы")
    @FindBy(xpath = ".//div[@class='creative-name__edit-name']//input")
    private TextInput groupName;

    @Name("Кнопка 'Сохранить' название группы")
    @FindBy(xpath = ".//button[contains(@class,'creative-name__save')]")
    private Button saveCreativesNameButton;

    private final String defaultCreativeSize = "240x400";
    private final String defaultCreativeName = "Новая группа";

    private WebElement getSpinLoader () {
        return spinLoader;
    }

    private void waitForSpinLoader(Matcher<WebElement> matcher) {
        waitForElement(getSpinLoader(), 6, matcher);
    }


    private void clickFirstTemplateItem() {
        creativeTemplates.get(0).click();
        waitForSpinLoader(not(isDisplayed()));
        takeScreenshot();
    }

    private void chooseCreativeWithName(String name) {
        CreativePreviewBlock block = creativePreviewBlocks
                .stream()
                .filter(x -> x.getGroupName().equals(name))
                .findFirst()
                .orElseThrow(() -> new DirectWebError("Не найден креатив с именем " + name));
        block.setCreativeCheckBoxState(true);
    }

    private void clickAddBannersToGroupAndWait() {
        addBannersToGroupButton.click();
        waitForSpinLoader(not(isDisplayed()));
        takeScreenshot();
    }

    private void createOneCreativeWithSize(String size, String name) {
        chooseCreativesSizeButton.click();
        for (CreativeFilterBlock block : creativeFiltersBlocks) {
            if (block.getCreativeSize().equals(size)) {
                block.selectCreativeCheckBoxState(true);
            } else {
                block.selectCreativeCheckBoxState(false);
            }
        }
        applyCreativesSizesButton.click();
        takeScreenshot();
        setCreativeGroupName(name);
        createBunnersButton.click();
        waitForSpinLoader(not(isDisplayed()));
        takeScreenshot();
    }

    private void setCreativeGroupName (String name) {
        editGroupName.click();
        groupName.getWrappedElement().click();
        groupName.clear();
        groupName.sendKeys(name);
        saveCreativesNameButton.click();
        takeScreenshot();
    }

    public void createCreative(String size, String name) {
        clickFirstTemplateItem();
        createOneCreativeWithSize(size, name);
        chooseCreativeWithName(name);
        clickAddBannersToGroupAndWait();
    }

    public void createCreative() {
        createCreative(defaultCreativeSize, defaultCreativeName);
    }

    public void createCreative(String name) {
        createCreative(defaultCreativeSize, name);
    }

    public void addCreativeFromGalleryByName(String name) {
        chooseCreativeWithName(name);
        clickAddBannersToGroupAndWait();
    }
}
