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

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

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.MobileAppCampaignSettingsEnum;
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.apiclient.errors.Api5ErrorDetails;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
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.MobileAppCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.MobileAppCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCpcMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyNetworkDefaultAddMap;
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.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.apache.commons.lang3.StringUtils.capitalize;
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 chicos on 07.09.2015.
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Позитивные сценарии проверки параметра WeeklySpendLimit при обновлении кампании со стратегией AverageCpc")
@Tag(TagDictionary.TRUNK)
public class StrategyAverageCpcWeeklySpendLimitTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;

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

    private MobileAppCampaignStrategyMap strategyMap;
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long goalId = MetrikaGoals.getGoalForCounter(counterId);
    private Long campaignId;

    @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.Parameters(name = "test = {0}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {"Пустое значение", null},
                {"Значение больше минимального", minLimit.getNext().bidLong().longValue()},
                {"Минимальное значение", minLimit.bidLong().longValue()},
                {"Максимальное значение", maxLimit.bidLong().longValue()}
        };
        return Arrays.asList(data);
    }

    @Before
    @Step("Подготовим данные для теста")
    public void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignId = api.userSteps.campaignSteps().addDefaultMobileAppCampaign();
        int shard = api.userSteps.clientFakeSteps().getUserShard(client);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps()
                .addCampMetrikaGoals(campaignId, goalId, 100L, 100L);

        strategyMap = new MobileAppCampaignStrategyMap()
                .withSearch(new MobileAppCampaignSearchStrategyMap()
                        .withBiddingStrategyType(MobileAppCampaignSearchStrategyTypeEnum.AVERAGE_CPC)
                        .withAverageCpc(new StrategyAverageCpcMap()
                                .withWeeklySpendLimit(weeklyLimit)
                                .withAverageCpc(averagePrice.longValue())))
                .withNetwork(new MobileAppCampaignNetworkStrategyMap().defaultNetworkDefault());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("1046")
    public void weeklyLimitTest() {
        api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withMobileAppCampaign(new MobileAppCampaignUpdateItemMap()
                                .withBiddingStrategy(strategyMap))),
                JavaOrPerlExpectedResult.java(ExpectedResult.success())
                        .perl(ExpectedResult.warnings(campaignId,
                        new Notification(10165, Api5ErrorDetails.PARAM_WILL_NOT_BE_CHANGED, capitalize(
                                StrategyNetworkDefaultAddMap.LIMIT_PERCENT)),
                        new Notification(10163, Api5ErrorDetails.SETTING_WILL_NOT_BE_CHANGED,
                                MobileAppCampaignSettingsEnum.MAINTAIN_NETWORK_CPC))));

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(campaignId))
                        .withFieldNames(CampaignFieldEnum.ID)
                        .withMobileAppCampaignFieldNames(MobileAppCampaignFieldEnum.BIDDING_STRATEGY));
        assumeThat("получили кампанию", campaigns, hasSize(1));
        MobileAppCampaignStrategy actualStrategy = campaigns.get(0).getMobileAppCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());

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