package ru.yandex.autotests.direct.api.campaigns.add.contentpromotion.strategy.maximumclicks;

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

import com.yandex.direct.api.v5.campaignsext.AddResponse;
import com.yandex.direct.api.v5.campaignsext.CampaignFieldEnum;
import com.yandex.direct.api.v5.campaignsext.CampaignGetItem;
import com.yandex.direct.api.v5.campaignsext.ContentPromotionCampaignFieldEnum;
import com.yandex.direct.api.v5.campaignsext.ContentPromotionCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaignsext.ContentPromotionCampaignStrategy;
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.campaignsext.AddRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.CampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.CampaignsSelectionCriteriaMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.ContentPromotionCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.GetRequestMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.StrategyMaximumClicksAddMap;
import ru.yandex.autotests.directapi.model.api5.campaignsext.StrategyMaximumClicksMap;
import ru.yandex.autotests.directapi.model.api5.general.ExpectedResult;
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;

/**
 * Created by pavryabov on 19.11.2015.
 */
@Aqua.Test
@Features(CampaignsFeatures.ADD)
@RunWith(Parameterized.class)
@Description("Позитивные сценарии проверки параметра WeeklySpendLimit при добавлении мобильной кампании со стратегией MaximumClicks")
@Tag(TagDictionary.TRUNK)
public class StrategyMaximumClicksWeeklySpendLimitTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;

    private static final Money minLimit = MoneyCurrency.get(currency).getMinWeeklyBudgetAmount();
    private static final Money maxLimit = MoneyCurrency.get(currency).getMaxWeeklyBudgetAmount();

    private ContentPromotionCampaignStrategyAddMap strategyMap;
    private ContentPromotionCampaignStrategyMap 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 weeklyLimit;

    @Parameterized.Parameter(value = 2)
    public Long bidCeiling;

    @Parameterized.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {"Значение больше минимального", minLimit.getNext().bidLong().longValue(), null},
                {"Минимальное значение", minLimit.bidLong().longValue(), null},
                {"Максимальное значение", maxLimit.bidLong().longValue(), null},
                {"Значение бюджета равно максимальной ставке", minLimit.bidLong().longValue(),
                        minLimit.bidLong().longValue()}
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        strategyMap = new ContentPromotionCampaignStrategyAddMap()
                .withSearch(new ContentPromotionCampaignSearchStrategyAddMap()
                        .withBiddingStrategyType(ContentPromotionCampaignSearchStrategyTypeEnum.WB_MAXIMUM_CLICKS)
                        .withWbMaximumClicks(new StrategyMaximumClicksAddMap()
                                .withWeeklySpendLimit(weeklyLimit)
                                .withBidCeiling(bidCeiling)))
                .withNetwork(new ContentPromotionCampaignNetworkStrategyAddMap().defaultServingOff());
        expectedStrategyMap = new ContentPromotionCampaignStrategyMap()
                .withSearch(new ContentPromotionCampaignSearchStrategyMap()
                        .withBiddingStrategyType(ContentPromotionCampaignSearchStrategyTypeEnum.WB_MAXIMUM_CLICKS)
                        .withWbMaximumClicks(new StrategyMaximumClicksMap()
                                .withWeeklySpendLimit(weeklyLimit)
                                .withBidCeiling(bidCeiling)))
                .withNetwork(new ContentPromotionCampaignNetworkStrategyMap().defaultServingOff());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("140")
    public void weeklyLimitTest() {
        AddResponse response = api.userSteps.campExtSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withContentPromotionCampaign(new ContentPromotionCampaignAddItemMap()
                                .withBiddingStrategy(strategyMap))),
                ExpectedResult.success());
        assumeThat("получили результаты добавления кампании", response.getAddResults(), hasSize(1));

        List<CampaignGetItem> campaigns = api.userSteps.campExtSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(response.getAddResults().get(0).getId()))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withContentPromotionCampaignFieldNames(ContentPromotionCampaignFieldEnum.BIDDING_STRATEGY));
        assumeThat("получили кампанию", campaigns, hasSize(1));
        ContentPromotionCampaignStrategy actualStrategy = campaigns.get(0).getContentPromotionCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

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