package ru.yandex.autotests.direct.api.campaigns.update.cpmbannercampaign.strategy.wb;

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

import com.yandex.direct.api.v5.campaigns.CpmBannerCampaignNetworkStrategyTypeEnum;
import org.junit.Before;
import org.junit.BeforeClass;
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.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.money.MoneyFormat;
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.campaigns.CampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyWbDecreasedPriceForRepeatedImpressionsMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyWbMaximumImpressionsMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.api5.general.JavaOrPerlExpectedResult;
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.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Сценарии проверки параметра SpendLimit при обновлении кампаний")
public class StrategiesWeeklySpendLimitTest {

    private static final String CLIENT = CampaignsLogins.CLIENT;
    private static final Currency CURRENCY = Currency.RUB;
    private static final MoneyCurrency MONEY_CURRENCY = MoneyCurrency.get(CURRENCY);

    private static final long AVERAGE_CPM = MONEY_CURRENCY.getMinCpmPrice().bidLong().longValue();
    private static final Money MIN_LIMIT = MONEY_CURRENCY.getMinDailyBudgetForPeriod().multiply(7);
    private static final Money MAX_LIMIT = MONEY_CURRENCY.getMaxWeeklyBudgetAmount();

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

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

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

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

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

    @Parameterized.Parameter(value = 2)
    public JavaOrPerlExpectedResult expectedResult;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {
                        "Нулевое значение",
                        0L,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(
                                        new Notification(4000,
                                                Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_LESS_WITHOUT_CURRENCY,
                                                "WeeklySpendLimit",
                                                MIN_LIMIT.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                                .perl(ExpectedResult.errors(
                                        new Notification(4000, Api5ErrorDetails.WEEKLY_LIMIT_SHOULD_BE_MORE_THAN,
                                                MIN_LIMIT.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                                MONEY_CURRENCY.getApiDescription())))},
                {
                        "Отрицательное значение",
                        -1L,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(
                                        new Notification(4000,
                                                Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_LESS_WITHOUT_CURRENCY,
                                                "WeeklySpendLimit",
                                                MIN_LIMIT.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                                .perl(ExpectedResult.errors(
                                new Notification(4000, Api5ErrorDetails.WEEKLY_LIMIT_SHOULD_BE_MORE_THAN,
                                        MIN_LIMIT.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                        MONEY_CURRENCY.getApiDescription())))},
                {
                        "Значение меньше минимального",
                        MIN_LIMIT.getPrevious().bidLong().longValue(),
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(
                                        new Notification(4000,
                                                Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_LESS_WITHOUT_CURRENCY,
                                                "WeeklySpendLimit",
                                                MIN_LIMIT.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                                .perl(ExpectedResult.errors(
                                new Notification(4000, Api5ErrorDetails.WEEKLY_LIMIT_SHOULD_BE_MORE_THAN,
                                        MIN_LIMIT.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                        MONEY_CURRENCY.getApiDescription())))},
                {
                        "Значение больше максимального",
                        MAX_LIMIT.getNext().bidLong().longValue(),
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_MUST_NOT_BE_GREATER_THAN,
                                        "WeeklySpendLimit",
                                        MAX_LIMIT.stringValue(MoneyFormat.WITHOUT_EXTRA_ZEROS))))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetails.WEEKLY_LIMIT_IS_TOO_HIGH,
                                        MAX_LIMIT.stringValue(MoneyFormat.TWO_DIGITS_POINT_SEPARATED),
                                        MONEY_CURRENCY.getApiDescription())))},
                {
                        "Значение равное минимальному",
                        MIN_LIMIT.bidLong().longValue(),
                        JavaOrPerlExpectedResult.both(ExpectedResult.success())},
                {
                        "Значение равное максимальному",
                        MAX_LIMIT.bidLong().longValue(),
                        JavaOrPerlExpectedResult.both(ExpectedResult.success())},
        };
        return Arrays.asList(data);
    }

    private Long campaignId;

    @BeforeClass
    @Step("Подготовим данные для теста")
    public static void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(CLIENT);
    }

    @Before
    public void createCampaign() {
        campaignId = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
    }

    @Test
    public void wbMaximumImpressionsTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withCpmBannerCampaign(new CpmBannerCampaignUpdateItemMap()
                                .withBiddingStrategy(new CpmBannerCampaignStrategyMap()
                                        .withSearch(new CpmBannerCampaignSearchStrategyMap().defaultServingOff())
                                        .withNetwork(
                                                new CpmBannerCampaignNetworkStrategyMap()
                                                        .withBiddingStrategyType(
                                                                CpmBannerCampaignNetworkStrategyTypeEnum.WB_MAXIMUM_IMPRESSIONS
                                                        )
                                                        .withWbMaximumImpressions(
                                                                new StrategyWbMaximumImpressionsMap()
                                                                        .withAverageCpm(AVERAGE_CPM)
                                                                        .withSpendLimit(spendLimit)))))),
                expectedResult);
    }

    @Test
    public void wbDecreasedPriceForRepeatedImpressionsTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withCpmBannerCampaign(new CpmBannerCampaignUpdateItemMap()
                                .withBiddingStrategy(new CpmBannerCampaignStrategyMap()
                                        .withSearch(new CpmBannerCampaignSearchStrategyMap().defaultServingOff())
                                        .withNetwork(
                                                new CpmBannerCampaignNetworkStrategyMap()
                                                        .withBiddingStrategyType(
                                                                CpmBannerCampaignNetworkStrategyTypeEnum.WB_DECREASED_PRICE_FOR_REPEATED_IMPRESSIONS
                                                        )
                                                        .withWbDecreasedPriceForRepeatedImpressions(
                                                                new StrategyWbDecreasedPriceForRepeatedImpressionsMap()
                                                                        .withAverageCpm(AVERAGE_CPM)
                                                                        .withSpendLimit(spendLimit)))))),
                expectedResult);
    }
}
