package ru.yandex.autotests.directintapi.bstransport.main.banner.parameters.domainid;

import java.util.Map;

import org.hamcrest.Matchers;
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.steps.DirectJooqDbSteps;
import ru.yandex.autotests.direct.utils.config.DirectTestRunProperties;
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.Banner;
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.api5.ads.AdAddItemMap;
import ru.yandex.autotests.directapi.model.api5.ads.TextAdAddMap;
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.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.CoreMatchers.allOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.lessThan;
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)
@Issue("https://st.yandex-team.ru/DIRECT-113655")
@Title("Транспорт: проверка отправки в БК SiteFilterID, DomainFilterID на баннере")
@Stories(StoriesNames.BANNER_PARAMS_PRICES)
@Features({FeatureNames.BANNERS})
public class BsTransportOfSiteDomainFilterId {

    private static final String LOGIN = Logins.LOGIN_TRANSPORT;

    private static int shard;
    private static DirectJooqDbSteps dbSteps;
    private static Long campaignId;
    private static Long adGroupId;

    private long bannerId;

    @ClassRule
    public static ApiSteps api = new ApiSteps().as(LOGIN);
    @ClassRule
    public static SemaphoreRule semaphore = Semaphore.getSemaphore();
    @Rule
    public Trashman trasher = new Trashman(api);

    @BeforeClass
    public static void init() {
        shard = api.userSteps.clientFakeSteps().getUserShard(LOGIN);
        dbSteps = new DirectJooqDbSteps().useShard(shard);
    }

    @Before
    public void setUp() {
        campaignId = api.userSteps.campaignSteps().addDefaultTextCampaign();
        api.userSteps.campaignFakeSteps().makeNewCampaignReadyForSendingToBS(campaignId);

        adGroupId = api.userSteps.adGroupsSteps().addDefaultGroup(campaignId);
        bannerId = api.userSteps.adsSteps().addDefaultTextAd(adGroupId);
        Long keywordId = api.userSteps.keywordsSteps().addRandomKeyword(adGroupId);

        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(bannerId);
        api.userSteps.groupFakeSteps().makeGroupFullyModerated(adGroupId);
        api.userSteps.phrasesFakeSteps().makeKeywordModerated(keywordId);
    }

    @Test
    @Title("В баннере ушли в БК поля SiteFilterID, DomainFilterID")
    public void bannerSiteDomainFilterIdSend() {
        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps()
                .sendNewCampaign(shard, campaignId);
        Campaign campaign = api.userSteps.getDarkSideSteps().getTransportSteps()
                .getClientDataRequestCampaign(resp, 0, campaignId);
        Context context = campaign.getContext(adGroupId);
        Banner banner = context.getBanner(bannerId);

        assertThat("SiteFilterID ушел в БК", banner.getSiteFilterID(), allOf(greaterThan(0),
                lessThan(Integer.MAX_VALUE)));
        assertThat("DomainFilterID ушел в БК", banner.getDomainFilterID(), allOf(greaterThan(0),
                lessThan(Integer.MAX_VALUE)));
    }

    @Test
    @Title("В баннере с визиткой и без ссылки в БК ушло поле DomainFilterID")
    public void bannerWithVcardDomainFilterIdSend() {
        Long secondBannerId = api.userSteps.adsSteps().addAd(new AdAddItemMap()
                .withTextAd(new TextAdAddMap().defaultTextAd()
                        .withText("тест DomainFilterID")
                        .withVCardId(api.userSteps.vCardsSteps().addDefaultVCard(LOGIN, campaignId)))
                .withAdGroupId(adGroupId), null);

        api.userSteps.bannersFakeSteps().makeBannerFullyModerated(secondBannerId);
        dbSteps.bannersSteps().setBannersHref(secondBannerId, "");
        RunBsTransportScriptResponse resp = api.userSteps.getDarkSideSteps().getTransportSteps()
                .sendNewCampaign(shard, campaignId);
        Map<String, Map> campaignRaw =
                api.userSteps.getDarkSideSteps().getTransportSteps().getRawClientDataLogEntriesForCampaignWithOmittedMdsMeta(resp, campaignId);
        assumeThat("в запросе к БК присутствует объект campaign", campaignRaw, notNullValue());

        // Значения для баннера берем из сырых логов, чтобы убедиться что ключи действительно
        // отсутствуют при пустом href
        Map banner =
                (Map) ((Map) ((Map) ((Map) ((Map) ((Map) ((Map) (campaignRaw.get(resp.getUuid()[0])).get("request")).get(
                        "ORDER")).get(campaignId.toString())).get("CONTEXT")).get(adGroupId.toString())).get("BANNER")).get(secondBannerId.toString());
        assertThat("в БК не отправлен параметр DomainFilterID", banner.containsKey("DomainFilterID"),
                Matchers.equalTo(true));
    }

}
