package ru.yandex.autotests.direct.api.campaigns.add.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.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.model.api5.campaigns.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CpmBannerCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyCpAverageCpvAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyCpDecreasedPriceForRepeatedImpressionsAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyCpMaximumImpressionsAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyCpMaximumImpressionsMap;
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;

/**
 * Created by gerdler on 16.09.2018.
 */
@Aqua.Test
@Features(CampaignsFeatures.ADD)
@RunWith(Parameterized.class)
@Description("Негативные сценарии проверки параметра StartDate при добавлении кампании со стратегиями с произвольным периодом")
public class StrategiesCustomPeriodStartDateNegativeTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;
    private static MoneyCurrency moneyCurrency = MoneyCurrency.get(currency);

    private static final long averageCpm = moneyCurrency.getMinCpmPrice().bidLong().longValue();
    private static final long averageCpv = moneyCurrency.getMinAvgCpv().bidLong().longValue();
    private static final long spendLimit = moneyCurrency.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 YESTERDAY = DateTime.now().minusDays(1).toString(DATE_PATTERN);
    private static final String TODAY = DateTime.now().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 JavaOrPerlExpectedResult expectedResult;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {
                        "Строка",
                        "строка",
                        END_DATE,
                        JavaOrPerlExpectedResult.both(ExpectedResult.errorsIgnoringDetails(
                                new Notification(4000, Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                        capitalize(StrategyCpMaximumImpressionsMap.START_DATE))
                        ))
                },
                {
                        "Нулевое значение",
                        "0000-00-00",
                        END_DATE,
                        JavaOrPerlExpectedResult.both(ExpectedResult.errorsIgnoringDetails(
                            new Notification(4000, Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                    capitalize(StrategyCpMaximumImpressionsMap.START_DATE))
                        ))
                },
                {
                        "Некорректная дата",
                        "2018-02-30",
                        END_DATE,
                        JavaOrPerlExpectedResult.both(ExpectedResult.errorsIgnoringDetails(
                                new Notification(4000, Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                        capitalize(StrategyCpMaximumImpressionsMap.START_DATE))
                        ))
                },
                {
                        "Дата со временем",
                        START_DATE + " 11:00:00",
                        END_DATE,
                        JavaOrPerlExpectedResult.both(ExpectedResult.errorsIgnoringDetails(
                                new Notification(4000, Api5ErrorDetails.DATE_INVALID_FORMAT_IN_FILED,
                                        capitalize(StrategyCpMaximumImpressionsMap.START_DATE))
                        ))
                },
                {
                        "Дата начала стратегии в прошлом",
                        YESTERDAY,
                        END_DATE,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errorsIgnoringDetails(
                                        new Notification(4000),
                                        new Notification(4000)
                                ))
                                .perl(ExpectedResult.errors(
                                        new Notification(4000, Api5ErrorDetails.DATE_CANT_BE_EARLIER_THAN_NOW,
                                                capitalize(StrategyCpMaximumImpressionsMap.START_DATE))
                                ))
                },
                {
                        "Дата начала стратегии позже даты окончания",
                        END_DATE,
                        START_DATE,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errorsIgnoringDetails(
                                        new Notification(6000),
                                        new Notification(4000),
                                        new Notification(4000)
                                ))
                                .perl(ExpectedResult.errors(
                                        new Notification(4000, Api5ErrorDetails.CP_START_DATE_CANT_BE_LATER_END_DATE,
                                                capitalize(StrategyCpMaximumImpressionsMap.START_DATE),
                                                capitalize(StrategyCpMaximumImpressionsMap.END_DATE)
                                        )
                                ))
                },
                {
                        "Дата начала стратегии раньше даты начала кампании",
                        TODAY,
                        END_DATE,
                        JavaOrPerlExpectedResult
                                .java(ExpectedResult.errorsIgnoringDetails(
                                        new Notification(4000),
                                        new Notification(4000)
                                ))
                                .perl(ExpectedResult.errors(
                                        new Notification(4000, Api5ErrorDetails.CP_START_DATE_CANT_BE_EARLY_THAN_CAMPAIGN_START_DATE)
                                ))
                },
        };
        return Arrays.asList(data);
    }

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

    @Test
    public void cpMaximumImpressionsStartDateNegativeTest() {
        api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withStartDate(START_DATE)
                        .withCpmBannerCampaign(new CpmBannerCampaignAddItemMap()
                                .withBiddingStrategy(new CpmBannerCampaignStrategyAddMap()
                                        .withSearch(new CpmBannerCampaignSearchStrategyAddMap().defaultServingOff())
                                        .withNetwork(
                                                new CpmBannerCampaignNetworkStrategyAddMap()
                                                        .withBiddingStrategyType(
                                                            CpmBannerCampaignNetworkStrategyTypeEnum.CP_MAXIMUM_IMPRESSIONS
                                                        )
                                                .withCpMaximumImpressions(
                                                        new StrategyCpMaximumImpressionsAddMap()
                                                                .withStartDate(startDate)
                                                                .withEndDate(endDate)
                                                                .withAverageCpm(averageCpm)
                                                                .withSpendLimit(spendLimit)
                                                                .withAutoContinue(YesNoEnum.YES)
                                                )

                                        )))),
                expectedResult);
    }

    @Test
    public void cpDecreasedPriceForRepeatedImpressionsStartDateNegativeTest() {
        api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withStartDate(START_DATE)
                        .withCpmBannerCampaign(new CpmBannerCampaignAddItemMap()
                                .withBiddingStrategy(new CpmBannerCampaignStrategyAddMap()
                                        .withSearch(new CpmBannerCampaignSearchStrategyAddMap().defaultServingOff())
                                        .withNetwork(
                                                new CpmBannerCampaignNetworkStrategyAddMap()
                                                        .withBiddingStrategyType(
                                                                CpmBannerCampaignNetworkStrategyTypeEnum.CP_DECREASED_PRICE_FOR_REPEATED_IMPRESSIONS
                                                        )
                                                        .withCpDecreasedPriceForRepeatedImpressions(
                                                                new StrategyCpDecreasedPriceForRepeatedImpressionsAddMap()
                                                                        .withStartDate(startDate)
                                                                        .withEndDate(endDate)
                                                                        .withAverageCpm(averageCpm)
                                                                        .withSpendLimit(spendLimit)
                                                                        .withAutoContinue(YesNoEnum.YES)
                                                        )

                                        )))),
                expectedResult);
    }


    @Test
    public void cpAverageCpvStartDateNegativeTest() {
        api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withStartDate(START_DATE)
                        .withCpmBannerCampaign(new CpmBannerCampaignAddItemMap()
                                .withBiddingStrategy(new CpmBannerCampaignStrategyAddMap()
                                        .withSearch(new CpmBannerCampaignSearchStrategyAddMap().defaultServingOff())
                                        .withNetwork(
                                                new CpmBannerCampaignNetworkStrategyAddMap()
                                                        .withBiddingStrategyType(
                                                                CpmBannerCampaignNetworkStrategyTypeEnum.CP_AVERAGE_CPV
                                                        )
                                                        .withCpAverageCpv(
                                                                new StrategyCpAverageCpvAddMap()
                                                                        .withStartDate(startDate)
                                                                        .withEndDate(endDate)
                                                                        .withAverageCpv(averageCpv)
                                                                        .withSpendLimit(spendLimit)
                                                                        .withAutoContinue(YesNoEnum.YES)
                                                        )

                                        )))),
                expectedResult);
    }
}
