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

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

import com.yandex.direct.api.v5.campaigns.CpmBannerCampaignNetworkStrategyTypeEnum;
import com.yandex.direct.api.v5.general.YesNoEnum;
import org.joda.time.DateTime;
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.MoneyCurrency;
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.StrategyCpDecreasedPriceForRepeatedImpressionsMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyCpMaximumImpressionsMap;
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;

import static org.apache.commons.lang3.StringUtils.capitalize;
import static ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap.DATE_PATTERN;

@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Негативные сценарии проверки параметра EndDate при обновлении кампании со стратегиями с произвольным " +
        "периодом")
public class StrategiesCustomPeriodEndDateNegativeTest {

    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 long DAILY_SPEND_LIMIT = MONEY_CURRENCY.getMinDailyBudgetForPeriod().bidLong().longValue();

    private static final String START_DATE = DateTime.now().plusDays(1).toString(DATE_PATTERN);
    private static final String END_DATE = DateTime.now().plusDays(2).toString(DATE_PATTERN);
    private static final String DAY_AFTER_END_DATE = DateTime.now().plusDays(3).toString(DATE_PATTERN);
    private static final String YESTERDAY = DateTime.now().minusDays(1).toString(DATE_PATTERN);

    @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 String startDate;

    @Parameterized.Parameter(value = 2)
    public String endDate;

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

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

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {
                        "Строка",
                        START_DATE,
                        "строка",
                        DAILY_SPEND_LIMIT,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_INVALID_FORMAT_IN_FILED, "EndDate")))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                capitalize(StrategyCpMaximumImpressionsMap.END_DATE))))
                },
                {
                        "Нулевое значение",
                        START_DATE,
                        "0000-00-00",
                        DAILY_SPEND_LIMIT,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_INVALID_FORMAT_IN_FILED, "EndDate")))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                capitalize(StrategyCpMaximumImpressionsMap.END_DATE))))
                },
                {
                        "Некорректная дата",
                        START_DATE,
                        "2018-02-30",
                        DAILY_SPEND_LIMIT,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_INVALID_FORMAT_IN_FILED, "EndDate")))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                capitalize(StrategyCpMaximumImpressionsMap.END_DATE))))
                },
                {
                        "Дата со временем",
                        START_DATE,
                        END_DATE + " 12:00:00",
                        DAILY_SPEND_LIMIT,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetailsJava.VALUE_INVALID_FORMAT_IN_FILED, "EndDate")))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                capitalize(StrategyCpMaximumImpressionsMap.END_DATE))))
                },
                {
                        "Дата начала и окончания стратегии в прошлом",
                        YESTERDAY,
                        YESTERDAY,
                        DAILY_SPEND_LIMIT,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                                Api5ErrorDetails.DATE_CANT_BE_EARLIER_THAN_NOW, "StartDate"),
                                        new Notification(5005,
                                                Api5ErrorDetailsJava.INVALID_VALUE_PATH_AND_VALUE, "EndDate",
                                                YESTERDAY))
                                )
                                .perl(ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.CP_DATE_CANT_BE_EARLY_THAN_TODAY,
                                capitalize(StrategyCpMaximumImpressionsMap.END_DATE))))
                },
                {
                        "Дата окончания стратегии больше даты окончания кампании",
                        START_DATE,
                        DAY_AFTER_END_DATE,
                        // разница между START_DATE и DAY_AFTER_END_DATE 3 дня, поэтому умножаем на 3
                        DAILY_SPEND_LIMIT * 3,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errors(new Notification(4000,
                                        Api5ErrorDetails.CP_END_DATE_CANT_BE_LATER_END_DATE)
                                ))
                                .perl(ExpectedResult.errors(new Notification(4000,
                                Api5ErrorDetails.CP_END_DATE_CANT_BE_LATER_END_DATE,
                                capitalize(StrategyCpMaximumImpressionsMap.END_DATE))))
                },
        };
        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 cpMaximumImpressionsEndDateNegativeTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withEndDate(END_DATE)
                        .withCpmBannerCampaign(new CpmBannerCampaignUpdateItemMap()
                                .withBiddingStrategy(new CpmBannerCampaignStrategyMap()
                                        .withSearch(new CpmBannerCampaignSearchStrategyMap().defaultServingOff())
                                        .withNetwork(
                                                new CpmBannerCampaignNetworkStrategyMap()
                                                        .withBiddingStrategyType(
                                                                CpmBannerCampaignNetworkStrategyTypeEnum.CP_MAXIMUM_IMPRESSIONS
                                                        )
                                                        .withCpMaximumImpressions(
                                                                new StrategyCpMaximumImpressionsMap()
                                                                        .withStartDate(startDate)
                                                                        .withEndDate(endDate)
                                                                        .withAverageCpm(AVERAGE_CPM)
                                                                        .withSpendLimit(spendLimit)
                                                                        .withAutoContinue(YesNoEnum.YES)
                                                        )

                                        )))),
                expectedResult);
    }

    @Test
    public void cpDecreasedPriceForRepeatedImpressionsEndDateNegativeTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withEndDate(END_DATE)
                        .withCpmBannerCampaign(new CpmBannerCampaignUpdateItemMap()
                                .withBiddingStrategy(new CpmBannerCampaignStrategyMap()
                                        .withSearch(new CpmBannerCampaignSearchStrategyMap().defaultServingOff())
                                        .withNetwork(
                                                new CpmBannerCampaignNetworkStrategyMap()
                                                        .withBiddingStrategyType(
                                                                CpmBannerCampaignNetworkStrategyTypeEnum
                                                                .CP_DECREASED_PRICE_FOR_REPEATED_IMPRESSIONS
                                                        )
                                                        .withCpDecreasedPriceForRepeatedImpressions(
                                                                new
                                                                StrategyCpDecreasedPriceForRepeatedImpressionsMap()
                                                                        .withStartDate(startDate)
                                                                        .withEndDate(endDate)
                                                                        .withAverageCpm(AVERAGE_CPM)
                                                                        .withSpendLimit(spendLimit)
                                                                        .withAutoContinue(YesNoEnum.YES)
                                                        )

                                        )))),
                expectedResult);
    }
}
