package ru.yandex.autotests.direct.api.campaigns.add.textcampaign.strategy.avaragecpa;

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

import com.yandex.direct.api.v5.campaigns.AddResponse;
import com.yandex.direct.api.v5.campaigns.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.CampaignGetItem;
import com.yandex.direct.api.v5.campaigns.TextCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.TextCampaignStrategy;
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.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.model.api5.campaigns.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpaAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpaMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
import ru.yandex.autotests.directapi.model.campaigns.MetrikaGoals;
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.allure.annotations.Step;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.matchers.beans.version5.BeanDifferMatcherV5.beanDifferV5;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Features(CampaignsFeatures.ADD)
@RunWith(Parameterized.class)
@Description("Позитивные сценарии проверки параметра AverageCpa при создании кампании со стратегией AverageCpa")
@Tag(TagDictionary.TRUNK)
public class StrategyAverageCpaAverageCpaTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;

    private static final Money minAverageCpa = MoneyCurrency.get(currency).getMinAveragePrice();
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);

    private TextCampaignStrategyMap expectedStrategyMap;


    @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 goalId;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Long[] goalIds = MetrikaGoals.getConterGoalIds(counterId, 1);
        Object[][] data = new Object[][]{
                {"По конкретной цели", goalIds[0]},
        };
        return Arrays.asList(data);
    }

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

        expectedStrategyMap = new TextCampaignStrategyMap()
                .withSearch(new TextCampaignSearchStrategyMap()
                        .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_CPA)
                        .withAverageCpa(new StrategyAverageCpaMap()
                                .withAverageCpa(minAverageCpa.getNext().bidLong().longValue())
                                .withGoalId(goalId)
                                .withBidCeiling(null)
                                .withWeeklySpendLimit(null)))
                .withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff());
    }

    @Test
    public void averageCpaCreateWithoutCounterTest() {
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                        .withSearch(new TextCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_CPA)
                                                .withAverageCpa(new StrategyAverageCpaAddMap()
                                                        .withAverageCpa(minAverageCpa.getNext().bidLong().longValue())
                                                        .withGoalId(goalId)
                                                        .withBidCeiling(null)
                                                        .withWeeklySpendLimit(null)))
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultServingOff())))),
                ExpectedResult.success());

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(response.getAddResults().get(0).getId()))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withTextCampaignFieldNames(TextCampaignFieldEnum.BIDDING_STRATEGY));


        assumeThat("получили результаты обновления кампании", response.getAddResults(), hasSize(1));

        assumeThat("получили кампанию", campaigns, hasSize(1));
        TextCampaignStrategy actualStrategy = campaigns.get(0).getTextCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

        assertThat("получили корректные стратегии", actualStrategy,
                beanDifferV5((TextCampaignStrategy) expectedStrategyMap.getBean()));
    }

    @Test
    public void  averageCpaCreateTest() {
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withTextCampaign(new TextCampaignAddItemMap()
                                .withCounterIds(counterId)
                                .withBiddingStrategy(new TextCampaignStrategyAddMap()
                                        .withSearch(new TextCampaignSearchStrategyAddMap()
                                                .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_CPA)
                                                .withAverageCpa(new StrategyAverageCpaAddMap()
                                                        .withAverageCpa(minAverageCpa.getNext().bidLong().longValue())
                                                        .withGoalId(goalId)
                                                        .withBidCeiling(null)
                                                        .withWeeklySpendLimit(null)))
                                        .withNetwork(new TextCampaignNetworkStrategyAddMap().defaultServingOff())))),
                ExpectedResult.success());

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(response.getAddResults().get(0).getId()))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withTextCampaignFieldNames(TextCampaignFieldEnum.BIDDING_STRATEGY));


        assumeThat("получили результаты обновления кампании", response.getAddResults(), hasSize(1));

        assumeThat("получили кампанию", campaigns, hasSize(1));
        TextCampaignStrategy actualStrategy = campaigns.get(0).getTextCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

        assertThat("получили корректные стратегии", actualStrategy,
                beanDifferV5((TextCampaignStrategy) expectedStrategyMap.getBean()));
    }
}
