package ru.yandex.autotests.direct.api.campaigns.update.textcampaign.strategy.averagecrr;

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.StrategyAverageCrr;
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 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.StrategyAverageCrrAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.StrategyAverageCrrMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.UpdateRequestMap;
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.allure.annotations.Description;
import ru.yandex.qatools.allure.annotations.Features;
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.UPDATE)
@RunWith(Parameterized.class)
@Description("Сценарии проверки редактирования кампании со стратегией AverageCrr")
public class StrategyAverageCrrPositiveTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Integer COUNTER_ID = MetrikaGoals.getCounterForLogin(client);
    private static final Money MIN_LIMIT = MoneyCurrency.get(Currency.RUB).getMinWeeklyBudgetAmount();
    private static final Money MAX_LIMIT = MoneyCurrency.get(Currency.RUB).getMaxWeeklyBudgetAmount();

    private Long campaignId;
    private TextCampaignStrategyMap strategyMap;
    private StrategyAverageCrrMap expectedStrategy;

    @ClassRule
    public static final ApiSteps api = new ApiSteps().as(client);

    @ClassRule
    public static final SemaphoreRule semaphore = Semaphore.getSemaphore();

    @Rule
    public Trashman trasher = new Trashman(api);

    @Parameterized.Parameter(value = 0)
    public Integer crr;
    
    @Parameterized.Parameter(value = 1)
    public Long goalId;

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

    @Parameterized.Parameters(name = "crr = {0}, goalId = {1}, weeklySpendLimit = {2}")
    public static Collection strategies() {
        Object[][] data = new Object[][] {
                {
                        StrategyAverageCrrAddMap.DEFAULT_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        StrategyAverageCrrAddMap.DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                // CRR
                {
                        StrategyAverageCrrAddMap.MIN_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        StrategyAverageCrrAddMap.DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                {
                        StrategyAverageCrrAddMap.MAX_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        StrategyAverageCrrAddMap.DEFAULT_WEEKLY_SPEND_LIMIT,
                },
                // SUM
                {
                        StrategyAverageCrrAddMap.DEFAULT_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        MIN_LIMIT.bidLong().longValue(),
                },
                {
                        StrategyAverageCrrAddMap.DEFAULT_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        MAX_LIMIT.bidLong().longValue(),
                },
                {
                        StrategyAverageCrrAddMap.DEFAULT_CRR,
                        MetrikaGoals.getGoalForCounter(COUNTER_ID),
                        null,
                }
        };
        return Arrays.asList(data);
    }

    @Before
    public void clearUnits() {
        api.userSteps.clientFakeSteps().fakeClearClientSpentUnits(client);
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        int shard = api.userSteps.clientFakeSteps().getUserShard(client);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps()
                .addCampMetrikaGoals(campaignId, goalId.longValue(), 100L, 100L);

        strategyMap = new TextCampaignStrategyMap()
                .withSearch(new TextCampaignSearchStrategyMap()
                        .withBiddingStrategyType(TextCampaignSearchStrategyTypeEnum.AVERAGE_CRR)
                        .withAverageCrr(new StrategyAverageCrrMap()
                                .withGoalId(goalId)
                                .withCrr(crr)
                                .withWeeklySpendLimit(weeklySpendLimit)
                        )
                ).withNetwork(new TextCampaignNetworkStrategyMap().defaultServingOff());
        
        expectedStrategy = new StrategyAverageCrrMap()
                .withCrr(crr)
                .withGoalId(goalId)
                .withWeeklySpendLimit(weeklySpendLimit);
    }
    
    @Test
    public void shouldUpdateStrategy() {
        UpdateResponse response = api.userSteps.campaignSteps().shouldGetResultOnUpdate(
                new UpdateRequestMap()
                        .withCampaigns(new CampaignUpdateItemMap()
                                .withId(campaignId)
                                .withTextCampaign(new TextCampaignUpdateItemMap()
                                        .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)
                        .withTextCampaignFieldNames(TextCampaignFieldEnum.BIDDING_STRATEGY));
        
        assumeThat("получили кампанию", campaigns, hasSize(1));
        TextCampaignStrategy actualStrategy = campaigns.get(0).getTextCampaign().getBiddingStrategy();
        assumeThat("получили стратегии кампании", actualStrategy, notNullValue());
        assumeThat("получили стратегию кампании для Search", actualStrategy.getSearch(), notNullValue());
        assertThat("получили корректные стратегии", actualStrategy.getSearch().getAverageCrr(),
                beanDifferV5((StrategyAverageCrr) expectedStrategy.getBean()));
    }
}
