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

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.MobileAppCampaignSearchStrategyTypeEnum;
import com.yandex.direct.api.v5.campaigns.MobileAppCampaignStrategy;
import com.yandex.direct.api.v5.campaigns.UpdateResponse;
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.directapi.apiclient.config.Semaphore;
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.StrategyMaximumAppInstallsMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
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.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 chicos on 05.10.2015.
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Позитивные сценарии проверки параметра WeeklySpendLimit при обновлении мобильной кампании со стратегией MaximumAppInstalls")
public class StrategyMaximumAppInstallsWeeklySpendLimitTest {
    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 MobileAppCampaignStrategyMap strategyMap;
    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.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);
        campaignId = api.userSteps.campaignSteps().addDefaultMobileAppCampaign();

        strategyMap = new MobileAppCampaignStrategyMap()
                .withSearch(new MobileAppCampaignSearchStrategyMap()
                        .withBiddingStrategyType(MobileAppCampaignSearchStrategyTypeEnum.WB_MAXIMUM_APP_INSTALLS)
                        .withWbMaximumAppInstalls(new StrategyMaximumAppInstallsMap()
                                .withWeeklySpendLimit(weeklyLimit)
                                .withBidCeiling(bidCeiling)))
                .withNetwork(new MobileAppCampaignNetworkStrategyMap().defaultServingOff());
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("1058")
    public void weeklyLimitTest() {
        UpdateResponse response = api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap().withCampaigns(new CampaignUpdateItemMap()
                        .withId(campaignId)
                        .withMobileAppCampaign(new MobileAppCampaignUpdateItemMap()
                                .withBiddingStrategy(strategyMap))),
                ExpectedResult.success());
        assumeThat("получили результаты обновления кампании", response.getUpdateResults(), hasSize(1));

        List<CampaignGetItem> campaigns = api.userSteps.campaignSteps().getCampaigns(
                new GetRequestMap().withSelectionCriteria(new CampaignsSelectionCriteriaMap()
                        .withIds(response.getUpdateResults().get(0).getId()))
                        .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.getBean()));
    }
}
