package ru.yandex.autotests.direct.api.bidmodifiers.get;


import java.util.Arrays;
import java.util.Collection;

import com.yandex.direct.api.v5.bidmodifiers.BidModifierGetItem;
import com.yandex.direct.api.v5.bidmodifiers.BidModifierLevelEnum;
import com.yandex.direct.api.v5.bidmodifiers.GetResponse;
import com.yandex.direct.api.v5.general.AgeRangeEnum;
import org.junit.AfterClass;
import org.junit.Before;
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.api.bidmodifiers.BidModifiersFeatures;
import ru.yandex.autotests.direct.api.bidmodifiers.BidModifiersLogins;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.BidModifierAddMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.BidModifiersSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.DemographicsAdjustmentMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.LimitOffsetMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.irt.testutils.allure.LogSteps;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static ch.lambdaj.Lambda.extract;
import static ch.lambdaj.Lambda.on;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Created by chicos on 09.07.15.
 */
@Aqua.Test
@Features(BidModifiersFeatures.GET)
@Tag(TagDictionary.TRUNK)
@Description("Проверка положительных сценариев для полей Limit и Offset")
@RunWith(Parameterized.class)
public class GetBidModifiersLimitOffsetTest {
    private static LogSteps log = LogSteps.getLogger(BidModifiersFeatures.class);
    private static final String client = BidModifiersLogins.SINGLE_CLIENT_GET;

    private static Long campaignID;
    private static long groupID;

    private static long bmID1;
    private static long bmID2;
    private static long bmID3;
    private static long bmID4;
    private static long bmID5;

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

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

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

    @Parameterized.Parameter(value = 0)
    public Long limit;

    @Parameterized.Parameter(value = 1)
    public Long offset;

    @Parameterized.Parameter(value = 2)
    public String description;

    @Parameterized.Parameter(value = 3)
    public BidModifiersSelectionCriteriaMap selectionCriteriaMap;

    @Parameterized.Parameter(value = 4)
    public Long[] expectedIds;

    @Parameterized.Parameter(value = 5)
    public Long expectedLimitedBy;

    private GetResponse getResponse;

    @Parameterized.Parameters(name = "criteria = {2} limit = {0}, offset = {1}")
    public static Collection limitsAndOffsets() {
        prepareBidModifiers();
        log.info("BidModifiers ready!");
        //выдача сортируется по id, т.к. id имеет префикс (10, 11, 12) в зависимости от типа корректировки,
        //корректировки будут выдаваться в порядке bmID2, bmID1, bmID4, bmID5, bmID3
        Long[] defaultBmIds = new Long[]{bmID1, bmID2, bmID3, bmID4, bmID5};
        Object[][] data = new Object[][]{
                //запрос по ID
                {null, null, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        defaultBmIds, null},
                {7L, null, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        defaultBmIds, null},
                {4L, null, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        new Long[]{bmID2, bmID1, bmID4, bmID5}, 4l},
                {null, 2L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        new Long[]{bmID3, bmID4, bmID5}, null},
                {null, 6L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        new Long[0], null},
                {null, 5L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        new Long[0], null},
                {null, 0L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        defaultBmIds, null},
                {3L, 1L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        new Long[]{bmID1, bmID4, bmID5}, 4l},
                {1L, 5L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        new Long[0], null},
                {4L, 3L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(defaultBmIds),
                        new Long[]{bmID5, bmID3}, null},
                {4L, 2L, "ID",
                        new BidModifiersSelectionCriteriaMap().withIds(
                                bmID1, bmID2, bmID3, bmID5, bmID4),
                        new Long[]{bmID3, bmID5, bmID4}, null},

                //запрос по groupID
                {null, null, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        defaultBmIds, null},
                {7L, null, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        defaultBmIds, null},
                {4L, null, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        new Long[]{bmID2, bmID1, bmID4, bmID5}, 4l},
                {null, 2L, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        new Long[]{bmID3, bmID4, bmID5}, null},
                {null, 6L, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        new Long[0], null},
                {null, 5L, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        new Long[0], null},
                {null, 0L, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        defaultBmIds, null},
                {3L, 1L, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        new Long[]{bmID1, bmID4, bmID5}, 4l},
                {1L, 5L, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        new Long[0], null},
                {4L, 3L, "groupID",
                        new BidModifiersSelectionCriteriaMap().withAdGroupIds(groupID),
                        new Long[]{bmID5, bmID3}, null},

                //запрос по campaignID
                {null, null, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        defaultBmIds, null},
                {7L, null, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        defaultBmIds, null},
                {4L, null, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        new Long[]{bmID2, bmID1, bmID4, bmID5}, 4l},
                {null, 2L, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        new Long[]{bmID3, bmID4, bmID5}, null},
                {null, 6L, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        new Long[0], null},
                {null, 5L, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        new Long[0], null},
                {null, 0L, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        defaultBmIds, null},
                {3L, 1L, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        new Long[]{bmID1, bmID4, bmID5}, 4l},
                {1L, 5L, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        new Long[0], null},
                {4L, 3L, "campaignID",
                        new BidModifiersSelectionCriteriaMap().withCampaignIds(campaignID.longValue()),
                        new Long[]{bmID5, bmID3}, null}
        };
        return Arrays.asList(data);
    }

    private static void prepareBidModifiers() {
        log.info("Подготовим корректировки ставок");
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignID = api.userSteps.campaignSteps().addDefaultTextCampaign(client);
        groupID = api.userSteps.adGroupsSteps().addDefaultGroup(campaignID);
        Integer conditionID = api.userSteps.retargetingSteps().addRandomRetargetingCondition(client);

        bmID1 = api.userSteps.bidModifiersSteps().addBidModifierDemographicsToGroup(groupID);
        bmID2 = api.userSteps.bidModifiersSteps().addBidModifierMobileToGroup(groupID);
        bmID3 = api.userSteps.bidModifiersSteps().addBidModifierRetargetingToGroup(conditionID.longValue(), groupID);
        bmID4 = api.userSteps.bidModifiersSteps().bidModifiersAdd(new BidModifierAddMap()
                .withDemographicsAdjustment(new DemographicsAdjustmentMap()
                        .withAge(AgeRangeEnum.AGE_45)
                        .withBidModifier(120))
                .withAdGroupId(groupID)).get(0);
        bmID5 = api.userSteps.bidModifiersSteps().bidModifiersAdd(new BidModifierAddMap()
                .withDemographicsAdjustment(new DemographicsAdjustmentMap()
                        .withAge(AgeRangeEnum.AGE_35_44)
                        .withBidModifier(130))
                .withAdGroupId(groupID)).get(0);
    }

    @Before
    public void getBidModifiers(){
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        getResponse = api.userSteps.bidModifiersSteps().bidModifiersGetRawResponse(
                new GetRequestMap()
                        .withSelectionCriteria(selectionCriteriaMap
                                .withLevels(BidModifierLevelEnum.AD_GROUP))
                        .withAllFieldNames()
                        .withPage(new LimitOffsetMap()
                                .withLimit(limit)
                                .withOffset(offset)));
        assumeThat("получили результат запроса корректировок ставок", getResponse.getBidModifiers(), notNullValue());
    }

    @Test
    public void limitOffsetTest() {
        //DIRECT-44340
        assertThat("вернулся корректный набор корректировок ставок",
                extract(getResponse.getBidModifiers(), on(BidModifierGetItem.class).getId()),
                containsInAnyOrder(expectedIds));
    }

    @Test
    public void limitedByTest() {
        //DIRECT-44328
        assertThat("значение параметра LimitedBy", getResponse.getLimitedBy(), equalTo(expectedLimitedBy));
    }

    @AfterClass
    public static void putCampaignToRemove(){
        //workaround для корректроного создания кампаний в параметризованном тесте
        api.userSteps.campaignSteps().putCampaignToQueue(client, campaignID);
    }
}
