package ru.yandex.autotests.directapi.keywords.get;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import com.yandex.direct.api.v5.general.ServingStatusEnum;
import com.yandex.direct.api.v5.keywords.KeywordFieldEnum;
import com.yandex.direct.api.v5.keywords.KeywordGetItem;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.steps.DirectJooqDbSteps;
import ru.yandex.autotests.directapi.ApiStories;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.keywords.KeywordsFeatures;
import ru.yandex.autotests.directapi.keywords.KeywordsLogins;
import ru.yandex.autotests.directapi.model.api5.keywords.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.keywords.KeywordsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by onotole on 26.12.16.
 * https://st.yandex-team.ru/TESTIRT-10841
 */
@Aqua.Test
@Features(KeywordsFeatures.GET)
@Stories(ApiStories.STATUS)
@Issue("https://st.yandex-team.ru/DIRECT-57834")
@Description("Проверка фильтрации по полю ServingStatus")
@RunWith(Parameterized.class)
public class GetBsRarelyLoadedFilteredTest {
    private static final String CLIENT = KeywordsLogins.SINGLE_CLIENT;

    private static long campaignId;
    private static long adGroupRarelyServed;
    private static long keywordRarelyServed;
    private static long adGroupEligible;
    private static long keywordEligible;
    private static long expectedKeywordId;
    private static Long eligibleAutotargetingId;
    private static Long rarelyServedAutotargetingId;
    private static Long expectedAutotargetingId;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(CLIENT);

    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();

    @Rule
    public Trashman trasher = new Trashman(api);

    @Parameterized.Parameter(0)
    public ServingStatusEnum servingStatus;

    @Parameterized.Parameters(name = "{0}")
    public static Collection<Object[]> testDate() {
        return Arrays.asList(new Object[][] {
                {ServingStatusEnum.RARELY_SERVED},
                {ServingStatusEnum.ELIGIBLE}
        });
    }

    @BeforeClass
    public static void setUp() {
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        adGroupEligible = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        adGroupRarelyServed = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        keywordEligible = api.userSteps.keywordsSteps().addDefaultKeyword(adGroupEligible);
        keywordRarelyServed = api.userSteps.keywordsSteps().addDefaultKeyword(adGroupRarelyServed);
        eligibleAutotargetingId = api.userSteps.keywordsSteps().addAutotargeting(adGroupEligible);
        rarelyServedAutotargetingId = api.userSteps.keywordsSteps().addAutotargeting(adGroupRarelyServed);

        DirectJooqDbSteps jooqDbSteps = api.userSteps.getDirectJooqDbSteps().useShardForLogin(CLIENT);
        jooqDbSteps.adGroupsSteps().setBsRarelyLoaded(adGroupEligible, false);
        jooqDbSteps.adGroupsSteps().setBsRarelyLoaded(adGroupRarelyServed, true);
    }

    @Before
    public void setExpectedKeywordIds() {
        if (servingStatus == ServingStatusEnum.RARELY_SERVED) {
            expectedKeywordId = keywordRarelyServed;
            expectedAutotargetingId = rarelyServedAutotargetingId;
        } else {
            expectedKeywordId = keywordEligible;
            expectedAutotargetingId = eligibleAutotargetingId;
        }
    }

    @Test
    public void checkFilterCampaignIds() {
        List<KeywordGetItem> keywordGetItems = api.userSteps.keywordsSteps().keywordsGet(
                new GetRequestMap().withSelectionCriteria(
                        new KeywordsSelectionCriteriaMap()
                                .withCampaignIds(campaignId)
                                .withServingStatuses(servingStatus))
                        .withFieldNames(KeywordFieldEnum.ID)
        );
        assumeThat("получили фразу и автотаргетинг",
                keywordGetItems, hasSize(2));
        assertThat("объекты с правильным значением ServingStatus прошли фильтрацию",
                keywordGetItems.stream().map((x) -> x.getId()).collect(Collectors.toList()),
                containsInAnyOrder(expectedKeywordId, expectedAutotargetingId)
        );
    }

    @Test
    public void checkFilterAdGroupIds() {
        List<KeywordGetItem> keywordGetItems = api.userSteps.keywordsSteps().keywordsGet(
                new GetRequestMap().withSelectionCriteria(
                        new KeywordsSelectionCriteriaMap()
                                .withAdGroupIds(adGroupEligible, adGroupRarelyServed)
                                .withServingStatuses(servingStatus))
                        .withFieldNames(KeywordFieldEnum.ID)
        );
        assumeThat("получили фразу и автотаргетинг",
                keywordGetItems, hasSize(2));
        assertThat("объекты с правильным значением ServingStatus прошли фильтрацию",
                keywordGetItems.stream().map((x) -> x.getId()).collect(Collectors.toList()),
                containsInAnyOrder(expectedKeywordId, expectedAutotargetingId)
        );
    }

    @Test
    public void checkFilterKeywordIds() {
        List<KeywordGetItem> keywordGetItems = api.userSteps.keywordsSteps().keywordsGet(
                new GetRequestMap().withSelectionCriteria(
                        new KeywordsSelectionCriteriaMap()
                                .withIds(keywordEligible, keywordRarelyServed, eligibleAutotargetingId, rarelyServedAutotargetingId)
                                .withServingStatuses(servingStatus))
                        .withFieldNames(KeywordFieldEnum.ID)
        );
        assumeThat("получили фразу и автотаргетинг",
                keywordGetItems, hasSize(2));
        assertThat("объекты с правильным значением ServingStatus прошли фильтрацию",
                keywordGetItems.stream().map((x) -> x.getId()).collect(Collectors.toList()),
                containsInAnyOrder(expectedKeywordId, expectedAutotargetingId)
        );
    }
}
