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

import java.util.List;

import com.yandex.direct.api.v5.adgroups.AdGroupFieldEnum;
import com.yandex.direct.api.v5.adgroups.DeleteResponse;
import com.yandex.direct.api.v5.adgroups.GetResponse;
import com.yandex.direct.api.v5.bidmodifiers.BidModifierGetItem;
import com.yandex.direct.api.v5.general.ActionResult;
import org.hamcrest.Matcher;
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.Api5ErrorDetails;
import ru.yandex.autotests.directapi.apiclient.errors.Api5ErrorDetailsJava;
import ru.yandex.autotests.directapi.model.api5.adgroups.AdGroupsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.adgroups.DeleteRequestMap;
import ru.yandex.autotests.directapi.model.api5.adgroups.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.IdsCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.general.Notification;
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 org.apache.commons.lang3.StringUtils.capitalize;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.equalTo;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
/**
 * Author pavryabov
 * Date 10.08.14
 * https://jira.yandex-team.ru/browse/TESTIRT-2022
 */
@Aqua.Test
@Features(AdGroupsFeatures.DELETE)
@Tag(TagDictionary.TRUNK)
public class DeleteTest {

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

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

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

    private static final Matcher<ActionResult> invalidIdErrorMatcher = either(ExpectedResult.errors(
            // perl
            new Notification(5005,
                    Api5ErrorDetails.FIELD_MUST_BE_POSITIVE_INTEGER, capitalize(IdsCriteriaMap.IDS)))
            .getActionResultMatcher()
    ).or(ExpectedResult.errors(
            // java
            new Notification(5005,
                    Api5ErrorDetailsJava.ID_MUST_BE_POSITIVE_INTEGER))
            .getActionResultMatcher());


    static Long campaignId;
    static Long notMineCampaignId;
    static Long notMineId;
    static Long deletedCampaignId;
    static Long archivedCampaignId;
    static Long groupFromDeletedCampaign;
    static Long groupFromArchivedCampaign;

    @BeforeClass
    public static void initTest() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AdGroupsLogins.CLIENT);
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(AdGroupsLogins.CLIENT_ELSE);
        api.as(AdGroupsLogins.CLIENT_ELSE);
        notMineCampaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(AdGroupsLogins.CLIENT_ELSE);
        notMineId = api.userSteps.adGroupsSteps().addDefaultGroup(notMineCampaignId);
        api.as(AdGroupsLogins.CLIENT);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(AdGroupsLogins.CLIENT);
        deletedCampaignId = api.userSteps.campaignSteps().addDefaultTextCampaign(AdGroupsLogins.CLIENT);
        groupFromDeletedCampaign = api.userSteps.adGroupsSteps().addDefaultGroup(deletedCampaignId);
        api.userSteps.campaignSteps().campaignsDelete(deletedCampaignId);
        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 deleteOneGroup() {
        Long id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id)),
                ExpectedResult.success(id)
        );
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("группа удалилась", response.getAdGroups().size(), equalTo(0));
    }

    @Test
    public void deleteTwoGroups() {
        Long id1 = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        Long id2 = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id1, id2)),
                ExpectedResult.success(id1),
                ExpectedResult.success(id2)
        );
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id1, id2)
                        )
                        .withFieldNames(AdGroupFieldEnum.ID)
        );
        assertThat("группа удалилась", response.getAdGroups().size(), equalTo(0));
    }

    @Test
    public void deleteWith0Id() {
        //DIRECT-33204
        DeleteResponse response = api.userSteps.adGroupsSteps().adGroupsDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(0L)));

        assertThat("Получена ожидаемая ошибка",
                response.getDeleteResults().get(0), invalidIdErrorMatcher);
    }

    @Test
    public void deleteNotMineGroup() {
        //DIRECT-35704
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(notMineId)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND))
        );
    }

    @Test
    public void deleteDeletedGroup() {
        Long id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adGroupsSteps().adGroupsDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id))
        );
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND))
        );
    }

    @Test
    public void deleteGroupFromDeletedCampaign() {
        //DIRECT-34637
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(groupFromDeletedCampaign)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND))
        );
    }

    @Test
    public void deleteGroupFromArchivedCampaign() {
        //DIRECT-34637
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(groupFromArchivedCampaign)),
                ExpectedResult.errors(new Notification(8300, Api5ErrorDetails.UNABLE_UPDATE_ARCHIVED_CAMPAGN))
        );
    }

    @Test
    public void deleteNotExistedGroup() {
        Long id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id + 100000)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND))
        );
    }

    @Test
    public void deleteWithNegativeId() {
        Long id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        DeleteResponse response = api.userSteps.adGroupsSteps().adGroupsDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(-id)));
        ActionResult deleteResult = response.getDeleteResults().get(0);

        assertThat("Получена ожидаемая ошибка", deleteResult, invalidIdErrorMatcher);
    }

    @Test
    public void deleteWithTwoInvalidIds() {
        Long id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id + 100000, id + 200000)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND))
        );
    }

    @Test
    public void deleteWithValidAndInvalidIds() {
        Long id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id + 10000, id)),
                ExpectedResult.errors(new Notification(8800, Api5ErrorDetails.GROUP_NOT_FOUND)),
                ExpectedResult.success(id)
        );
        GetResponse response = api.userSteps.adGroupsSteps().adGroupsGet(
                new GetRequestMap()
                        .withSelectionCriteria(
                                new AdGroupsSelectionCriteriaMap()
                                        .withIds(id)
                        )
                        .withFieldNames(
                                AdGroupFieldEnum.ID
                        )
        );
        assertThat("группа удалилась", response.getAdGroups().size(), equalTo(0));
    }

    @Test
    public void deleteGroupTwoTimesInRequest() {
        //DIRECT-33205
        Long id = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(id, id)),
                ExpectedResult.errors(new Notification(9800)),
                ExpectedResult.errors(new Notification(9800))
        );
    }

    @Test
    public void tryDeleteGroupWithAd() {
        Long idNotEmpty = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.adsSteps().addDefaultTextAd(idNotEmpty);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(idNotEmpty)),
                ExpectedResult.errors(new Notification(8301, Api5ErrorDetails.UNABLE_DELETED_GROUP_CONTAINED_OBJECTS))
        );
    }

    @Test
    public void tryDeleteGroupWithKeyword() {
        Long idNotEmpty = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        api.userSteps.keywordsSteps().addDefaultKeyword(idNotEmpty);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(idNotEmpty)),
                ExpectedResult.errors(new Notification(8301, Api5ErrorDetails.UNABLE_DELETED_GROUP_CONTAINED_OBJECTS))
        );
    }

    @Test
    //DIRECT-72749
    public void tryDeleteGroupWithDeletedAutotargeting() {
        Long idNotEmpty = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        Long aId = api.userSteps.keywordsSteps().addAutotargeting(idNotEmpty);
        api.userSteps.keywordsSteps().keywordsDelete(aId);
        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(idNotEmpty)),
                ExpectedResult.success(idNotEmpty)
        );
    }

    @Test
    //DIRECT-81001
    public void tryDeleteGroupWithBidModifier() {
        Long idNotEmpty = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        Long bidModifierId = api.userSteps.bidModifiersSteps().addBidModifierDemographicsToGroup(idNotEmpty);

        api.userSteps.adGroupsSteps().shouldGetResultOnDelete(
                new DeleteRequestMap().withSelectionCriteria(new IdsCriteriaMap().withIds(idNotEmpty)),
                ExpectedResult.success(idNotEmpty)
        );
        List<BidModifierGetItem> bidModifiers = api.userSteps.bidModifiersSteps().bidModifiersGetById(bidModifierId);

        assertThat("корректировка удалилась", bidModifiers.size(), equalTo(0));
    }
}
