package ru.yandex.autotests.directintapi.bstransport.main.phrase.parameters.priority;
import java.util.Arrays;
import java.util.Collection;

import org.junit.BeforeClass;
import org.junit.ClassRule;
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.utils.money.Currency;
import ru.yandex.autotests.direct.utils.tags.TagDictionary;
import ru.yandex.autotests.directapi.darkside.Logins;
import ru.yandex.autotests.directapi.darkside.connection.Semaphore;
import ru.yandex.autotests.directapi.darkside.model.RunBsTransportScriptResponse;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Campaign;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Context;
import ru.yandex.autotests.directapi.darkside.model.bslogs.clientdata.Phrase;
import ru.yandex.autotests.directapi.model.api5.campaigns.CampaignUpdateItemMap;
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.rules.ApiSteps;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Stories;
import ru.yandex.qatools.allure.annotations.Title;
import ru.yandex.qatools.hazelcast.SemaphoreRule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static ru.yandex.autotests.directapi.darkside.model.bslogs.AutoBudgetPriority.MEDIUM;
import static ru.yandex.autotests.directapi.model.campaigns.MetrikaGoals.getRandom;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка отправки в БК дефолтного приоритета фразы для автоматических стратегий на поиске")
@Stories(StoriesNames.PHRASE_PARAMS_PRIORITY)
@Features(FeatureNames.PHRASES)
@RunWith(Parameterized.class)
public class BsTransportOfDefaultPriorityForSearchStrategiesTest {

    private static final String login = Logins.LOGIN_TRANSPORT;

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

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

    private static int shard;

    @Parameterized.Parameter
    public TextCampaignSearchStrategyMap searchStrategy;

    @Parameterized.Parameters(name = "стратегия в РСЯ = {0}")
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][]{
                {new TextCampaignSearchStrategyMap().defaultWbMaximumClicks(Currency.RUB)},
                {new TextCampaignSearchStrategyMap().defaultAverageCpa(Currency.RUB, 0L)},
                {new TextCampaignSearchStrategyMap().defaultAverageCpc(Currency.RUB)},
                {new TextCampaignSearchStrategyMap().defaultWbMaximumConversionRate(Currency.RUB, 0L)}
        };
        return Arrays.asList(data);
    }

    @BeforeClass
    public static void beforeClass() {
        shard = api.userSteps.clientFakeSteps().getUserShard(login);
    }

    @Test
    @Title("Отправка в БК дефолтного приоритета фразы для автоматических стратегий на поиске")
    public void testTransportOfDefaultPriorityForSearchStrategies() {
        int goalId = getRandom();

        TextCampaignNetworkStrategyMap networkStrategy =
                new TextCampaignNetworkStrategyMap().defaultNetworkDefault();
        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).campaignsSteps()
                .addCampMetrikaGoals(cid, (long) goalId, 100L, 100L);
        api.userSteps.campaignSteps().campaignsUpdate(new UpdateRequestMap()
                .withCampaigns(new CampaignUpdateItemMap()
                        .withId(cid)
                        .withTextCampaign(new TextCampaignUpdateItemMap()
                                .withBiddingStrategy(new TextCampaignStrategyMap()
                                        .withSearch(searchStrategy)
                                        .withNetwork(networkStrategy)))));
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultTextAd(pid);
        Long bidsId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(bidsId);

        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        Context context = campaign != null ? campaign.getContext(pid) : null;
        Phrase phrase = context != null ? context.getPhrase(bidsId) : null;

        assumeThat("в БК отправлена фраза", phrase, notNullValue());

        assertThat("отправленный в БК дефолтный приоритет ставки соответствует ожидаемому",
                phrase.getAutoBudgetPriority(), equalTo(MEDIUM.transportValue()));
    }
}
