package ru.yandex.autotests.directintapi.bstransport.main.phrase.parameters.bid;

import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.utils.money.Money;
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.TextCampaignNetworkStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.campaigns.TextCampaignSearchStrategyAddMap;
import ru.yandex.autotests.directapi.model.api5.keywords.KeywordAddMap;
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.irt.testutils.allure.TestSteps.assertThat;
import static ru.yandex.autotests.irt.testutils.allure.TestSteps.assumeThat;

@Aqua.Test
@Tag(TagDictionary.TRUNK)
@Tag(TagDictionary.RELEASE)
@Title("Транспорт: проверка отправки в БК ставки в РСЯ для новой фразы " +
        "в синхронизированной группе (стратегия в РСЯ = maximum coverage)")
@Stories(StoriesNames.PHRASE_PARAMS_BID)
@Features(FeatureNames.PHRASES)
public class BsTransportOfContextBidOfMaxCoverStrategyForNewPhraseInSyncedGroupTest {

    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;
    private static final float PRICE = 40.0f;
    private static final float CONTEXT_PRICE = 25.0f;

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


    @Test
    @Title("Отправка в БК ставки в РСЯ для новой фразы в синхронизированной группе " +
            "(для ручных стратегий в РСЯ)")
    public void testTransportOfPhraseContextBidForNewPhraseInSyncedGroup() {
        TextCampaignSearchStrategyAddMap searchStrategy =
                new TextCampaignSearchStrategyAddMap().defaultHighestPosition();
        TextCampaignNetworkStrategyAddMap networkStrategy =
                new TextCampaignNetworkStrategyAddMap().defaultMaximumCoverage();

        Long cid = api.userSteps.campaignSteps().addDefaultTextCampaignWithStrategies(searchStrategy, networkStrategy);
        Long pid = api.userSteps.adGroupsSteps().addDefaultGroup(cid);
        Long bid = api.userSteps.adsSteps().addDefaultTextAd(pid);
        Long syncedBidsId = api.userSteps.keywordsSteps().keywordsAdd(new KeywordAddMap()
                .defaultKeyword()
                .withAdGroupId(pid)
                .withBid(Money.valueOf(PRICE + 1).bidLong().longValue())
                .withContextBid(Money.valueOf(CONTEXT_PRICE + 1).bidLong().longValue())).get(0);
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(syncedBidsId);

        api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);

        Long newBidsId = api.userSteps.keywordsSteps().keywordsAdd(new KeywordAddMap()
                .defaultKeyword()
                .withAdGroupId(pid)
                .withBid(Money.valueOf(PRICE).bidLong().longValue())
                .withContextBid(Money.valueOf(CONTEXT_PRICE).bidLong().longValue())).get(0);

        api.userSteps.phrasesFakeSteps().makeKeywordModerated(newBidsId);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);

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

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

        assertThat("отправленная в БК ставка в РСЯ соответствует ожидаемой",
                newPhrase.getPriceContext(), equalTo((double) CONTEXT_PRICE));
    }
}
