package ru.yandex.autotests.direct.api.campaigns.archive;

import java.util.List;

import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import com.yandex.direct.api.v5.campaigns.CampaignStateGetEnum;
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.campaigns.CampaignsFeatures;
import ru.yandex.autotests.direct.api.campaigns.CampaignsLogins;
import ru.yandex.autotests.direct.utils.money.Currency;
import ru.yandex.autotests.direct.utils.money.Money;
import ru.yandex.autotests.direct.utils.money.MoneyCurrency;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.apiclient.config.Semaphore;
import ru.yandex.autotests.directapi.common.api45.CreateNewSubclientResponse;
import ru.yandex.autotests.directapi.model.Logins;
import ru.yandex.autotests.directapi.model.api5.Action;
import ru.yandex.autotests.directapi.model.api5.campaigns.ArchiveRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.IdsCriteriaMap;
import ru.yandex.autotests.directapi.model.campaigns.Status;
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.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.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;

/**
 * Created by gerdler on 23.09.18.
 */
@Aqua.Test
@Features(CampaignsFeatures.ARCHIVE)
@Description("Проверка позитивных сценариев архивирования медийных кампаний")
@Tag(TagDictionary.TRUNK)
public class ArchiveCpmBannerCampaignsPositiveTest {

    private static final String client = CampaignsLogins.SINGLE_CLIENT_ARCHIVE;
    private static final String agencyLogin = Logins.AGENCY_LOGIN_ACCOUNT_ENABLED;

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

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

    private static Long campaignIdCpmBanner;
    private static Long campaignIdText;
    private static Long campaignID;
    private static Long campaignID1;
    private static Long campaignID2;
    private static Long campaignAgency;

    private static String subClient;
    private static final Currency currency = Currency.RUB;
    private static final Money sumToAdd = MoneyCurrency.get(currency).getMinInvoiceAmount();

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

    @BeforeClass
    public static void initTest() {
        api.as(client).userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignID = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        campaignID1 = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        campaignID2 = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        campaignIdCpmBanner = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        campaignIdText = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignSteps()
                .campaignsSuspend(campaignID, campaignID1, campaignID2, campaignIdCpmBanner, campaignIdText);

        //Создадим субклиента
        CreateNewSubclientResponse createNewSubclientResponse =
                api.as(agencyLogin).userSteps.clientSteps()
                        .createNewAgencySubClient("subClient", agencyLogin, currency);
        subClient = createNewSubclientResponse.getLogin();
        //Создадим субклиенту кампанию и включим ОС
        campaignAgency = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign(subClient);
        api.userSteps.clientFakeSteps().enableAgencyWallet(agencyLogin);
        Integer accountID = api.userSteps.financeSteps().enableAndGetSharedAccount(subClient);
        api.userSteps.campaignFakeSteps().sendFakeNotificationFromBalance(
                accountID,
                sumToAdd.addVAT().floatValue(),
                currency);

        api.userSteps.campaignSteps().campaignsSuspend(subClient, campaignAgency);
    }

    @Test
    public void archiveSingleCpmBannerTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID)),
                ExpectedResult.success(campaignID));
        CampaignGetItem campaign = api.userSteps.campaignSteps().campaignsGet(campaignID, CampaignFieldEnum.STATE);
        assertThat("корректное значение поля State после архивирования медийной кампании", campaign.getState(),
                equalTo(CampaignStateGetEnum.ARCHIVED));
    }

    @Test
    public void archiveTwoCpmBannerCampaignsTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID1, campaignID2)),
                ExpectedResult.success(campaignID1),
                ExpectedResult.success(campaignID2));
        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(campaignID1, campaignID2);
        List<CampaignStateGetEnum> states = extract(campaigns, on(CampaignGetItem.class).getState());
        assertThat("корректное значение поля State после архивирования медийной кампании", states,
                everyItem(equalTo(CampaignStateGetEnum.ARCHIVED)));
    }

    @Test
    public void archiveCampaignsDifferentTypesTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignIdCpmBanner, campaignIdText)),
                ExpectedResult.success(campaignIdCpmBanner),
                ExpectedResult.success(campaignIdText));
        List<CampaignGetItem> campaigns =
                api.userSteps.campaignSteps().getCampaigns(campaignIdCpmBanner, campaignIdText);
        List<CampaignStateGetEnum> states = extract(campaigns, on(CampaignGetItem.class).getState());
        assertThat("корректное значение поля State после архивирования кампаний разных типов",
                states, everyItem(equalTo(CampaignStateGetEnum.ARCHIVED)));
    }

    @Test
    @Description("Заархивируем медийную кампанию, отправленную на модерацию")
    public void archiveCpmBannerCampaignSentToModerationTest() {
        Long campaignID = api.as(client).userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        api.userSteps.campaignFakeSteps().setStatusModerate(campaignID, Status.READY);
        api.userSteps.campaignSteps().campaignsSuspend(campaignID);

        api.userSteps.campaignSteps().shouldGetResultOn(
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID)),
                ExpectedResult.success(campaignID));
    }

    @Test
    @Description("Заархивируем медийную кампанию, у которой время последнего показа более часа")
    public void archiveSuspendedCampaignLastShowMoreThanAnHourTest() {
        Long campaignID = api.as(client).userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        api.userSteps.campaignFakeSteps().makeCampaignStopped(campaignID);
        api.userSteps.campaignFakeSteps().setLastShowTimeAnHourAndMinuteAgo(campaignID);

        api.userSteps.campaignSteps().shouldGetResultOn(
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignID)),
                ExpectedResult.success(campaignID));
    }

    @Test
    @Description("Заархивируем последнюю медийную кампанию с подключенным ОС с деньгами")
    public void archiveLastCampaignFromAccountTest() {
        api.as(agencyLogin).userSteps.campaignSteps().shouldGetResultOn(
                subClient,
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignAgency)),
                ExpectedResult.success(campaignAgency));
    }
}
