package ru.yandex.autotests.direct.api.campaigns.update.dynamictextcampaign.strategy;

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.DynamicTextCampaignFieldEnum;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignNetworkStrategy;
import com.yandex.direct.api.v5.campaigns.DynamicTextCampaignStrategy;
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.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.DynamicTextCampaignNetworkStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignSearchStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignStrategyMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.DynamicTextCampaignUpdateItemMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.GetRequestMap;
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.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 07.09.2015.
 */
@Aqua.Test
@Features(CampaignsFeatures.UPDATE)
@RunWith(Parameterized.class)
@Description("Проверка возможности использования целей Метрики при обновлении динамической текстовой кампании " +
        "стратегиями требующими GoalId")
public class StrategyMetrikaGoalIdUpdateTest {
    private static final String client = CampaignsLogins.CLIENT;
    private static final Currency currency = Currency.RUB;
    private static final Integer counterId = MetrikaGoals.getCounterForLogin(client);
    private static final Long[] goalIds = MetrikaGoals.getConterGoalIds(counterId, 2);
    private static DynamicTextCampaignStrategyMap 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 String placeName;

    @Parameterized.Parameter(value = 2)
    public String strategyName;

    @Parameterized.Parameter(value = 3)
    public DynamicTextCampaignNetworkStrategyMap networkStrategy;

    @Parameterized.Parameter(value = 4)
    public DynamicTextCampaignSearchStrategyMap searchStrategy;

    @Parameterized.Parameter(value = 5)
    public DynamicTextCampaignNetworkStrategyMap expectedNetworkStrategy;

    @Parameterized.Parameters(name = "test = {0}, place = {1}, strategy = {2}")
    public static Collection strategies() {
        Object[][] data = new Object[][]{
                {"Одна цель", "Search", "AverageCpa",
                        new DynamicTextCampaignNetworkStrategyMap().defaultServingOff(),
                        new DynamicTextCampaignSearchStrategyMap().defaultAverageCpa(currency, goalIds[1]),
                        new DynamicTextCampaignNetworkStrategyMap().defaultServingOff()},
                {"Одна цель", "Search", "MaximumConversionRate",
                        new DynamicTextCampaignNetworkStrategyMap().defaultServingOff(),
                        new DynamicTextCampaignSearchStrategyMap().defaultWbMaximumConversionRate(currency,
                                goalIds[1]),
                        new DynamicTextCampaignNetworkStrategyMap().defaultServingOff()},
                {"Одна цель", "Search", "AverageRoi",
                        new DynamicTextCampaignNetworkStrategyMap().defaultServingOff(),
                        new DynamicTextCampaignSearchStrategyMap().defaultAverageRoi(goalIds[1]),
                        new DynamicTextCampaignNetworkStrategyMap().defaultServingOff()}
        };
        return Arrays.asList(data);
    }

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

        strategyMap = new DynamicTextCampaignStrategyMap()
                .withSearch(searchStrategy)
                .withNetwork(networkStrategy);
    }

    @Test
    @ru.yandex.qatools.allure.annotations.TestCaseId("961")
    public void strategyNetworkTest() {
        api.userSteps.campaignSteps().campaignsUpdateWithCheck(new CampaignUpdateItemMap()
                .withId(campaignId)
                .withDynamicTextCampaign(new DynamicTextCampaignUpdateItemMap()
                        .withBiddingStrategy(strategyMap)));

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

        assertThat("получили корректную стратегию Network", actualStrategy.getNetwork(),
                beanDifferV5((DynamicTextCampaignNetworkStrategy) expectedNetworkStrategy.getBean()));
    }
}
