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 pavryabov on 19.11.15.
 */
@Aqua.Test
@Features(CampaignsFeatures.ARCHIVE)
@Description("Проверка позитивных сценариев архивирования динамических текстовых кампаний")
@Tag(TagDictionary.TRUNK)
public class ArchiveDynamicTextCampaignsPositiveTest {

    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 campaignIdDynamicText;
    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().addDefaultDynamicTextCampaign();
        campaignID1 = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        campaignID2 = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        campaignIdDynamicText = api.userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        campaignIdText = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignSteps()
                .campaignsSuspend(campaignID, campaignID1, campaignID2, campaignIdDynamicText, 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);

        /*Account account = api.userSteps.financeSteps().getAccount(subClient);
        api.userSteps.payAccountWithBalance(subClient, sumToAdd.addVAT().floatValue(), currency);
        ConditionFactories.NOTIFY_ORDER2.until(api.userSteps.financeSteps().accountAmountChangedOnSum(account, sumToAdd.floatValue()));*/

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

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("313")
    public void archiveSingleMobileCampaignTest() {
        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
    @ru.yandex.qatools.allure.annotations.TestCaseId("314")
    public void archiveTwoMobileCampaignsTest() {
        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
    @ru.yandex.qatools.allure.annotations.TestCaseId("309")
    public void archiveCampaignsDifferentTypesTest() {
        api.as(client).userSteps.campaignSteps().shouldGetResultOn(
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignIdDynamicText, campaignIdText)),
                ExpectedResult.success(campaignIdDynamicText),
                ExpectedResult.success(campaignIdText));
        List<CampaignGetItem> campaigns =
                api.userSteps.campaignSteps().getCampaigns(campaignIdDynamicText, campaignIdText);
        List<CampaignStateGetEnum> states = extract(campaigns, on(CampaignGetItem.class).getState());
        assertThat("корректное значение поля State после архивирования кампаний разных типов",
                states, everyItem(equalTo(CampaignStateGetEnum.ARCHIVED)));
    }

    @Test
    @Description("Заархивируем мобильную кампанию, отправленную на модерацию")
    @ru.yandex.qatools.allure.annotations.TestCaseId("312")
    public void archiveMobileCampaignSentToModerationTest() {
        Long campaignID = api.as(client).userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        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("Заархивируем мобильную кампанию, у которой время последнего показа более часа")
    @ru.yandex.qatools.allure.annotations.TestCaseId("310")
    public void archiveSuspendedCampaignLastShowMoreThanAnHourTest() {
        Long campaignID = api.as(client).userSteps.campaignSteps().addDefaultDynamicTextCampaign();
        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("Заархивируем последнюю мобильную кампанию с подключенным ОС с деньгами")
    @ru.yandex.qatools.allure.annotations.TestCaseId("311")
    public void archiveLastCampaignFromAccountTest() {
        api.as(agencyLogin).userSteps.campaignSteps().shouldGetResultOn(
                subClient,
                Action.ARCHIVE,
                new ArchiveRequestMap().withSelectionCriteria(new IdsCriteriaMap()
                        .withIds(campaignAgency)),
                ExpectedResult.success(campaignAgency));
    }
}
