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

import java.util.ArrayList;
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.data.textresources.Strings;
import ru.yandex.autotests.direct.web.objects.banners.McBannerInfoWeb;
import ru.yandex.autotests.direct.web.objects.groups.McGroupInfoWeb;
import ru.yandex.autotests.direct.web.pages.banners.blocks.edit.bem.EditGroupWithMcBannerBlockBem;
import ru.yandex.autotests.direct.web.steps.UserSteps;
import ru.yandex.autotests.direct.web.util.DirectWebError;
import ru.yandex.autotests.irt.testutils.beandiffer2.comparestrategy.defaultcomparestrategy.DefaultCompareStrategies;
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 static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static ru.yandex.autotests.direct.web.steps.CommonSteps.waitForElement;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;
import static ru.yandex.autotests.irt.testutils.beandiffer2.BeanDifferMatcher.beanDiffer;
import static ru.yandex.autotests.irt.testutils.beandiffer2.beanfield.BeanFieldPath.newPath;
import static ru.yandex.qatools.htmlelements.matchers.WebElementMatchers.isEnabled;

@NamedUrls({
        @NamedUrl(name = "edit.bannergroup.mcbanner.for.client",
                url = "/registered/main.pl?cmd=editMediaAdGroups&bid={2}&cid={1}&ulogin={3}&adgroup_ids={4}"),
})
public class AddAdGroupsMcBannerPage extends BasePageObject {
    @Name("Групповые изменения")
    @FindBy(xpath = ".//button[contains(@class, 'b-edit-groups-mass-actions__popup-toggle-link ')]")
    private Button groupChangesButton;

    @Name("Кнопка '< Назад'")
    @FindBy(xpath = ".//button[contains(@class, 'p-multiedit') and contains(@class, 'back-button')]")
    private Button backButton;

    @Name("Кнопка 'Вперед >'")
    @FindBy(xpath = ".//button[contains(@class, 'p-multiedit')" +
            " and (contains(@class, 'submit-button') or contains(@class, 'next-button'))]")
    private Button nextButton;

    private List<EditGroupWithMcBannerBlockBem> groups;

    public Button getNextButton() {
        return nextButton;
    }

    public void clickNextAndExpectSuccess() {
        clickNext();
        UserSteps.getInstance(UserSteps.class, config).inOperatingSystem()
                .waitForPageTitle(startsWith(Strings.TITLE_CAMPAIGN_VIEW));
    }

    public void clickNext() {
        waitForElement(nextButton.getWrappedElement(), 5, isEnabled());
        nextButton.click();
    }

    public void waitUntilNextButtonWillBeEnabled(Matcher<WebElement> matcher) {
        waitForElement(nextButton.getWrappedElement(), 10, matcher);
    }

    public void clickBack() {
        backButton.click();
    }

    public void clickGroupChangesButton() {
        groupChangesButton.click();
    }

    public void fillGroups(List<McGroupInfoWeb> groupsInfo) {
        groupsHaveExpectedSize(groupsInfo);
        for (int i = 0; i < groupsInfo.size(); i++) {
            EditGroupWithMcBannerBlockBem currentGroup = groups.get(i);
            currentGroup.setConfig(config);
            currentGroup.fillParameters(groupsInfo.get(i));
        }
    }

    public void checkGroups(List<McGroupInfoWeb> expectedGroups) {
        groupsHaveExpectedSize(expectedGroups);
        List<McGroupInfoWeb> result = new ArrayList<>();
        for (int i = 0; i < expectedGroups.size(); i++) {
            result.add(groups.get(i).getFormFieldsAccording(expectedGroups.get(i)));
        }
        assertThat("группы соответствуют ожиданиям", result, beanDiffer(expectedGroups).useCompareStrategy(
                DefaultCompareStrategies
                        .allFieldsExcept(newPath("\\d+", "banners", "\\d+", "imageAd", "imageAdLoadType"))));
    }

    public void addBannerToGroup(Long groupId, McBannerInfoWeb bannerInfoWeb) {
        EditGroupWithMcBannerBlockBem group = groups.stream()
                .filter(x -> x.getAdGroupId().equals(groupId))
                .findFirst()
                .orElseThrow(() -> new DirectWebError("Не найдена группа № " + groupId));
        group.setConfig(config);
        group.addNewBannerToGroup(bannerInfoWeb);
    }

    private void groupsHaveExpectedSize(List<McGroupInfoWeb> groupInfoWebs) {
        assumeThat("количество групп соответствует ожидаемому", groupInfoWebs.size(), equalTo(groups.size()));
    }

}
