package ru.yandex.autotests.direct.api.campaigns.add.mobilecampaign.strategy.averagecpc;

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.MobileAppCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignNetworkStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignStrategy;
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.MobileAppCampaignAddItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpcAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpcMap;
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 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 chicos on 05.10.2015.
 */
@Aqua.Test
@Features(CampaignsFeatures.ADD)
@RunWith(Parameterized.class)
@Description("Позитивные сценарии проверки параметра AveragePrice при добавлении мобильной кампании со стратегией AverageCpc")
@Tag(TagDictionary.TRUNK)
public class StrategyAverageCpcAveragePriceTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;

    private static final Money minPrice = MoneyCurrency.get(currency).getMinAveragePrice();
    private static final Money maxPrice = MoneyCurrency.get(currency).getMaxPrice();
    private static final Money weeklyLimit =
            MoneyCurrency.get(currency).getMaxWeeklyBudgetAmount().divide(10f).bidLong();

    private MobileAppCampaignStrategyAddMap strategyMap;
    private MobileAppCampaignStrategyMap 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 averagePrice;

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

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

    @Before
    @Step("Подготовим данные для теста")
    public void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        strategyMap = new MobileAppCampaignStrategyAddMap()
                .withSearch(new MobileAppCampaignSearchStrategyAddMap()
                        .withBiddingStrategyType(MobileAppCampaignSearchStrategyTypeEnum.AVERAGE_CPC)
                        .withAverageCpc(new StrategyAverageCpcAddMap()
                                .withWeeklySpendLimit(weeklySpeedLimit)
                                .withAverageCpc(averagePrice)))
                .withNetwork(new MobileAppCampaignNetworkStrategyAddMap().defaultNetworkDefault());
        expectedStrategyMap = new MobileAppCampaignStrategyMap()
                .withSearch(new MobileAppCampaignSearchStrategyMap()
                        .withBiddingStrategyType(MobileAppCampaignSearchStrategyTypeEnum.AVERAGE_CPC)
                        .withAverageCpc(new StrategyAverageCpcMap()
                                .withWeeklySpendLimit(weeklySpeedLimit)
                                .withAverageCpc(averagePrice)))
                .withNetwork(new MobileAppCampaignNetworkStrategyMap().defaultNetworkDefault());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("157")
    public void averagePriceTest() {
        AddResponse response = api.userSteps.campaignSteps().shouldGetResultOnAdd(
                new AddRequestMap().withCampaigns(new CampaignAddItemMap()
                        .defaultCampaignAddItem()
                        .withMobileAppCampaign(new MobileAppCampaignAddItemMap()
                                .withBiddingStrategy(strategyMap))),
                ExpectedResult.success());

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(response.getAddResults().get(0).getId()))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withMobileAppCampaignFieldNames(MobileAppCampaignFieldEnum.BIDDING_STRATEGY));
        assumeThat("получили кампанию", campaigns, hasSize(1));

        assertThat("получили корректные стратегии", campaigns.get(0).getMobileAppCampaign().getBiddingStrategy(),
                beanDifferV5((MobileAppCampaignStrategy) expectedStrategyMap
                        .withNetwork(new MobileAppCampaignNetworkStrategyMap()
                                .withBiddingStrategyType(MobileAppCampaignNetworkStrategyTypeEnum.NETWORK_DEFAULT))
                        .getBean()));
    }
}
