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

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.yandex.direct.api.v5.adgroups.AdGroupFieldEnum;
import com.yandex.direct.api.v5.adgroups.AdGroupStatusSelectionEnum;
import com.yandex.direct.api.v5.adgroups.GetResponse;
import com.yandex.direct.api.v5.general.StateEnum;
import com.yandex.direct.api.v5.general.StatusEnum;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.api.adgroups.AdGroupsFeatures;
import ru.yandex.autotests.direct.api.adgroups.AdGroupsLogins;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.apiclient.errors.Api5Error;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetailsJava;
import ru.yandex.autotests.directapi.darkside.model.Status;
import ru.yandex.autotests.directapi.model.api5.adgroups.AdGroupGetItemMap;
import ru.yandex.autotests.directapi.model.api5.adgroups.AdGroupsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.adgroups.GetRequestMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static java.util.Arrays.asList;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.direct.utils.matchers.BeanEquals.beanEquals;
import static ru.yandex.autotests.directapi.apiclient.errors.Path.path;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

/**
 * Author pavryabov
 * Date 26.06.14
 * https://jira.yandex-team.ru/browse/TESTIRT-2022
 */
@Aqua.Test
@Features(AdGroupsFeatures.GET)
@Tag(TagDictionary.TRUNK)
public class SelectionCriteriaTest {

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

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

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

    static Long campaignId;
    static Long campaignIdElse;
    static Long campaignIdNoGroups;
    static Long archivedCampaignId;
    static Long id;
    static Long idElse1;
    static Long idElse2;
    static Long groupFromArchivedCampaign;

    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AdGroupsLogins.CLIENT);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(AdGroupsLogins.CLIENT);
        id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        campaignIdElse = api.userSteps.campaignSteps().addDefaultTextCampaign(AdGroupsLogins.CLIENT);
        idElse1 = api.userSteps.adGroupsSteps().addDefaultGroup(campaignIdElse);
        idElse2 = api.userSteps.adGroupsSteps().addDefaultGroup(campaignIdElse);
        api.userSteps.adsSteps().addDefaultTextAd(idElse2, AdGroupsLogins.CLIENT);
        api.userSteps.groupFakeSteps().setStatusModerate(idElse2, Status.YES);
        api.userSteps.groupFakeSteps().setStatusPostModerate(idElse2, Status.YES);
        campaignIdNoGroups = api.userSteps.campaignSteps().addDefaultTextCampaign(AdGroupsLogins.CLIENT);
        archivedCampaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(AdGroupsLogins.CLIENT);
        groupFromArchivedCampaign = api.userSteps.adGroupsSteps().addDefaultGroup(archivedCampaignId);
        api.userSteps.campaignSteps().campaignsSuspend(archivedCampaignId);
        api.userSteps.campaignSteps().campaignsArchive(archivedCampaignId);
    }

    @Before
    public void clearSpentUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AdGroupsLogins.CLIENT);
    }

    @Test
    public void getWithEmptySelectionCriteria() {
        //DIRECT-33771
        //DIRECT-35689
        api.userSteps.adGroupsSteps().expectErrorOnAdGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(new AdGroupsSelectionCriteriaMap())
                        .withFieldNames(AdGroupFieldEnum.CAMPAIGN_ID),
                new Api5Error(4001, Api5ErrorDetails.REQUESTED_FIELDS_IN_SELECTION_CRITERIA)
        );
    }

    @Test
    public void selectionCriteriaWithOnlyStatus() {
        //DIRECT-33771
        //DIRECT-35689
        api.userSteps.adGroupsSteps().expectErrorOnAdGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(new AdGroupsSelectionCriteriaMap()
                                .withStatuses(AdGroupStatusSelectionEnum.DRAFT))
                        .withFieldNames(AdGroupFieldEnum.CAMPAIGN_ID),
                new Api5Error(4001, Api5ErrorDetails.REQUESTED_FIELDS_IN_SELECTION_CRITERIA)
        );
    }

    @Test
    public void selectionCriteriaWithIdsWithOneElement() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void selectionCriteriaWithArrayOfIds() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id, idElse1)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(asList(
                        beanEquals(new AdGroupGetItemMap().withId(id).getBean()),
                        beanEquals(new AdGroupGetItemMap().withId(idElse1).getBean()))));
    }

    @Test
    public void selectionCriteriaWithIdTwoTimesInOneRequest() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id, id)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void selectionCriteriaWithMaxLengthIds() {
        Long[] ids = new Long[AdGroupsSelectionCriteriaMap.IDS_MAX_LENGTH];
        Arrays.fill(ids, id);
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(ids)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void selectionCriteriaWithCampaignIdsWithOneElement() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignId)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void selectionCriteriaWithArrayOfCampaignIds() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignId, campaignIdElse)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(asList(
                        beanEquals(new AdGroupGetItemMap().withId(id).getBean()),
                        beanEquals(new AdGroupGetItemMap().withId(idElse1).getBean()),
                        beanEquals(new AdGroupGetItemMap().withId(idElse2).getBean()))));
    }

    @Test
    public void selectionCriteriaWithCampaignIdTwoTimesInOneRequest() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignId, campaignId)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void selectionCriteriaWithCampaignWithTwoGroups() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignIdElse)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(asList(
                        beanEquals(new AdGroupGetItemMap().withId(idElse1).getBean()),
                        beanEquals(new AdGroupGetItemMap().withId(idElse2).getBean()))));
    }

    @Test
    public void selectionCriteriaWithCampaignWithoutGroups() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignIdNoGroups)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("вернулось правильное количество групп", response.getAdGroups().size(), equalTo(0));
    }

    @Test
    public void selectionCriteriaWithMaxLengthCampaignIds() {
        Long[] campaignIds = new Long[AdGroupsSelectionCriteriaMap.CAMPAIGN_IDS_MAX_LENGTH];
        Arrays.fill(campaignIds, campaignId);
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignIds)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void campaignWithOneGroupAndThisGroup() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id)
                                        .withCampaignIds(campaignId)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void campaignWithTwoGroupsAndOneOfThisGroups() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(idElse1)
                                        .withCampaignIds(campaignIdElse)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(idElse1).getBean())));
    }

    @Test
    public void campaignWithOneGroupAndOtherGroup() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(idElse1)
                                        .withCampaignIds(campaignId)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("вернулось правильное количество групп", response.getAdGroups().size(), equalTo(0));
    }

    @Test
    public void campaignWithOneGroupAndThisGroupAndOtherGroup() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id, idElse1)
                                        .withCampaignIds(campaignId)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void campaignWithOneGroupAndThisGroupAndOtherCampaign() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id)
                                        .withCampaignIds(campaignId, campaignIdElse)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(id).getBean())));
    }

    @Test
    public void selectionCriteriaWithArchivedCampaignId() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(archivedCampaignId)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(groupFromArchivedCampaign).getBean())));
    }

    @Test
    public void selectionCriteriaWithGroupFromArchivedCampaign() {
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(groupFromArchivedCampaign)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(groupFromArchivedCampaign).getBean())));
    }

    @Test
    public void selectionCriteriaWithOneStatus() {
        //DIRECT-35691
        StatusEnum status = api.userSteps.adGroupsSteps().getGroupStatus(idElse1);
        assumeThat("одна из групп имеет статус DRAFT", status, equalTo(StatusEnum.DRAFT));
        status = api.userSteps.adGroupsSteps().getGroupStatus(idElse2);
        assumeThat("одна из групп имеет статус ACCEPTED", status, equalTo(StatusEnum.ACCEPTED));
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignIdElse)
                                        .withStatuses(AdGroupStatusSelectionEnum.ACCEPTED)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(
                        beanEquals(new AdGroupGetItemMap().withId(idElse2).getBean())));
    }

    @Test
    public void selectionCriteriaWithTwoStatuses() {
        StatusEnum status = api.userSteps.adGroupsSteps().getGroupStatus(idElse1);
        assumeThat("одна из групп имеет статус DRAFT", status, equalTo(StatusEnum.DRAFT));
        status = api.userSteps.adGroupsSteps().getGroupStatus(idElse2);
        assumeThat("одна из групп имеет статус ACCEPTED", status, equalTo(StatusEnum.ACCEPTED));
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignIdElse)
                                        .withStatuses(AdGroupStatusSelectionEnum.ACCEPTED,
                                                AdGroupStatusSelectionEnum.DRAFT)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("AdGroups.get вернул правильный набор групп", response.getAdGroups(),
                contains(asList(
                        beanEquals(new AdGroupGetItemMap().withId(idElse1).getBean()),
                        beanEquals(new AdGroupGetItemMap().withId(idElse2).getBean()))));
    }

    @Test
    public void selectionCriteriaWithMoreThanMaxLengthIds() {
        //DIRECT-34574
        Long[] ids = new Long[AdGroupsSelectionCriteriaMap.IDS_MAX_LENGTH + 1];
        Arrays.fill(ids, id);
        api.userSteps.adGroupsSteps().expectErrorOnAdGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(ids)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID),
                new Api5Error(4001,
                        Api5ErrorDetailsJava.MAX_IDS_IN_SELECTION,
                        path(GetRequestMap.SELECTION_CRITERIA, AdGroupsSelectionCriteriaMap.IDS)));
    }

    @Test
    public void selectionCriteriaWithMoreThanMaxLengthCampaignIds() {
        //DIRECT-34574
        Long[] campaignIds = new Long[AdGroupsSelectionCriteriaMap.CAMPAIGN_IDS_MAX_LENGTH + 1];
        Arrays.fill(campaignIds, campaignId);
        api.userSteps.adGroupsSteps().expectErrorOnAdGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withCampaignIds(campaignIds)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID),
                new Api5Error(4001,
                        Api5ErrorDetailsJava.MAX_IDS_IN_SELECTION,
                        path(GetRequestMap.SELECTION_CRITERIA,
                                AdGroupsSelectionCriteriaMap.CAMPAIGN_IDS)));
    }

    @Test
    public void selectionCriteriaWithStatusArchived() {
        //DIRECT-40422
        api.userSteps.adGroupsSteps().expectErrorOnAdGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(new AdGroupsSelectionCriteriaMap()
                                .withIds(id)
                                .withStatuses(StateEnum.ARCHIVED.value()))
                        .withFieldNames(AdGroupFieldEnum.CAMPAIGN_ID),
                new Api5Error(8000,
                        Api5ErrorDetailsJava.ELEMENT_OF_ARRAY_CONTAINS_INCORRECT_ENUMERATE_VALUE,
                        path(GetRequestMap.SELECTION_CRITERIA, AdGroupsSelectionCriteriaMap.STATUSES),
                        Stream.of(StatusEnum.ACCEPTED, StatusEnum.DRAFT, StatusEnum.MODERATION,
                                StatusEnum.REJECTED, StatusEnum.PREACCEPTED)
                                .map(Object::toString)
                                .collect(Collectors.joining(", "))));
    }
}
