package ru.yandex.autotests.directintapi.bstransport.main.group.parameters.desktoppricecoef;

import java.util.Map;

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

import ru.yandex.aqua.annotations.project.Aqua;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.BannersPerformanceStatusmoderate;
import ru.yandex.autotests.direct.db.models.jooq.ppc.enums.PerfCreativesStatusmoderate;
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.model.User;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.BidModifierAddMap;
import ru.yandex.autotests.directapi.model.api5.bidmodifiers.DesktopAdjustmentMap;
import ru.yandex.autotests.directapi.rules.ApiSteps;
import ru.yandex.autotests.directapi.rules.Trashman;
import ru.yandex.autotests.directintapi.bstransport.FeatureNames;
import ru.yandex.autotests.directintapi.bstransport.StoriesNames;
import ru.yandex.autotests.directintapi.bstransport.TransportHelpSteps;
import ru.yandex.qatools.Tag;
import ru.yandex.qatools.allure.annotations.Features;
import ru.yandex.qatools.allure.annotations.Issue;
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.RELEASE)
@Title("Транспорт: проверка отправки параметра DesktopPriceCoef на уровне группы, добавление")
@Stories(StoriesNames.GROUP_PARAMS_DESKTOPPRICECOEF)
@Features(FeatureNames.GROUPS)
@Issue("https://st.yandex-team.ru/DIRECT-86815")
public class BsTransportOfGroupDesktopPriceCoefAddTest {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;
    private static final Integer DESKTOP_PRICE_COEF = 50;

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

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

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

    private static TransportHelpSteps helpSteps = new TransportHelpSteps(api);

    private static int shard;
    private Context context;


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

    @Before
    public void before() {
        Long cid = api.userSteps.campaignSteps().addDefaultCpmBannerCampaign();
        Long pid = api.userSteps.adGroupsSteps().addDefaultCpmBannerKeywordsAdGroup(cid);
        Long creativeId = api.userSteps.getDirectJooqDbSteps().useShard(shard).perfCreativesSteps()
                .saveDefaultCanvasCreativesForClient(Long.parseLong(User.get(LOGIN).getClientID()));
        Long bid = api.userSteps.adsSteps().addDefaultCpmBannerAdBuilderAd(pid, creativeId);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).perfCreativesSteps()
                .setStatusModerate(creativeId, PerfCreativesStatusmoderate.Yes);
        api.userSteps.getDirectJooqDbSteps().useShard(shard).bannersPerformanceSteps()
                .setCreativeStatusModerate(cid, pid, bid, BannersPerformanceStatusmoderate.Yes);
        Long keywordId = api.userSteps.keywordsSteps().addDefaultKeyword(pid);
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(cid);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(pid);
        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bid);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);

        RunBsTransportScriptResponse
                resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendNewCampaign(shard, cid);
        Map<String, Map> contextMap = helpSteps.getContextMap(resp, cid, pid);
        assumeThat("в БК отправлен контекст (группа)", contextMap, notNullValue());
        assumeThat("в БК отправлена корректировка DesktopPriceCoef со значение undef на уровне группы",
                contextMap.get(Context.DESKTOP_PRICE_COEF), equalTo(null));

        api.userSteps.bidModifiersSteps().bidModifiersAdd(
                new BidModifierAddMap()
                        .withDesktopAdjustment(new DesktopAdjustmentMap()
                                .withBidModifier(DESKTOP_PRICE_COEF)
                        )
                        .withAdGroupId(pid)
        );

        resp = api.userSteps.getDarkSideSteps().getTransportSteps().sendCampaign(shard, cid);

        Campaign campaign =
                api.userSteps.getDarkSideSteps().getTransportSteps().getClientDataRequestCampaign(resp, cid);
        context = campaign != null ? campaign.getContext(pid) : null;
        assumeThat("в БК отправлен контекст (группа)", context, notNullValue());
    }

    @Test
    @Title("Отправка в БК корректировки DesktopPriceCoef на уровне группы при ее добавлении")
    public void testTransportOfGroupDesktopPriceCoef() {
        assertThat("отправленная в БК корректировка desktopPriceCoef на уровне группы соответствует ожидаемой",
                context.getDesktopPriceCoef(), equalTo(DESKTOP_PRICE_COEF.toString()));
    }
}
